Skip to content
Advertisement

Working with 2 arrays with different lengths Numpy Python

Is there a way I could modify the function down below so that it could compute arrays with different length sizes. the length of Numbers array is 7 and the length of the Formating is 5. The code down below compares if any number in Formating is between two values and if it the case then it sums the values that are in between. So for the first calculation since no element in Numbers is between 0, 2 the result will be 0. Link to code was derived from: issue.

Code:

Numbers = np.array([3, 4, 5, 7, 8, 10,20])
Formating = np.array([0, 2 , 5, 12, 15])
x = np.sort(Numbers);
l = np.searchsorted(x, Formating, side='left')
mask=(Formating[:-1,None]<=Numbers)&(Numbers<Formating[1:,None])
N=Numbers[:,None].repeat(5,1).T
result= np.ma.masked_array(N,~mask)
result = result.filled(0)
result = np.sum(result, axis=1)

Expected output:

[ 0  7 30  0]

Advertisement

Answer

Here’s an approach with bincounts. Note that you have your x and l messed-up, and I recalled that you could/should use digitize:

# Formating goes here
x = np.sort(Formating);

# digitize
l = np.digitize(Numbers, x)

# output:
np.bincount(l, weights=Numbers)

Out:

array([ 0.,  0.,  7., 30.,  0., 20.])

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement