How To Extract Specific Numbers From Numpy Arrays Based On The Repetition Of Numbers
I have two numpy arrays and want to extract some specific parts of them. These arrays are: arr_A=np.arange(17, 29) arr_B=np.arange(17, 27) These arrays are number of some points.
Solution 1:
Based on your comments and clarifications, here is a way you can solve this.
How it works -
fetch_sublists()
generator breaks the list intosublists
and frontpads
each with 0s.get_stars()
calls the abovegenerator
to construct the matrix bystacking
the arrays, flips to face the zeros upwards based onorientation
, and saves it tom
- Uses this orientation to find the first non zero elements from the top direction and saves it to
star
- Rotates the matrix in the required direction and overwrites it on
m
- Finally returns both matrix as
mat
and side elements asstar
.
#Generates the sublists with padding0
def fetch_sublists(arr, rep):
itr = iter(arr)
maxlen = np.max(rep)
for size in rep:
sublist = []
for _ in range(size):
sublist.append(next(itr))
yield np.pad(sublist, maxlen-size)[:maxlen]
#Constructs the matrix based on orientation and returns the side elements
def get_stars(arr, rep, orientation='right'):
if orientation=='right':
m = np.flipud(list(fetch_sublists(arr, rep)))
star_elements = m[(m!=0).argmax(0), np.arange(m.shape[1])]
m = np.rot90(m,k=-1)
else:
m = np.array(list(fetch_sublists(arr, rep)))
star_elements = np.flip(m[(m!=0).argmax(0), np.arange(m.shape[1])])
m = m.T
return m, star_elements
#Case 1 with right side orientation
mat, star = get_stars(arr_A, rep_A, 'right')
print('Matrix -')
print(mat)
print('')
print('Star elements -')
print(star)
Matrix -
[[17 21 0 0 0][18 22 0 0 0][19 23 25 0 0][20 24 26 27 28]]
Star elements -
[21 22 25 28]
#Case 2 with left side orientation
mat, star = get_stars(arr_B, rep_B, 'left')
print('Matrix -')
print(mat)
print('')
print('Star elements -')
print(star)
Matrix -
[[ 0 0 22][ 0 18 23][ 0 19 24][ 0 20 25][17 21 26]]
Star elements -
[17 20 19 18 22]
IIUC, you are trying to break a list into uneven chunks as the first part. Note, that you cant use numpy to store the final array since it needs same elements in each object in each dimension, and here each of the sublists contains different number of elements.
You can use generators for this as -
def fetch_sublists(arr, rep):
itr = iter(arr)
for size in rep:
sublist = []
for _ in range(size):
sublist.append(next(itr))
yield sublist
print(list(fetch_sublists(arr_A, rep_A)))
print(list(fetch_sublists(arr_B, rep_B)))
[[17, 18, 19, 20], [21, 22, 23, 24], [25, 26], [27], [28]][[17], [18, 19, 20, 21], [22, 23, 24, 25, 26]]
What is unclear is what you want after that in the second part. Will request you elaborate on that so I can update my answer accordingly.
Post a Comment for "How To Extract Specific Numbers From Numpy Arrays Based On The Repetition Of Numbers"