0

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]
4
  • What's wrong with that code? Commented Mar 12, 2021 at 2:28
  • @hpaulj it doesn't run :-). Should have been N=Numbers[:,None].repeat(4,1).T. That said x and l are redudant, and wrong! Commented Mar 12, 2021 at 2:51
  • and all that result stuff seems overkilled. (mask * Numbers[None, :]).sum(axis=1) works fine. That said, this series of questions from OP look like an XY-problem. Commented Mar 12, 2021 at 2:55
  • x and l are from a different solution, mask is what I proposed. The use of 5 in N is left over from when Formatting had 6 terms; obviously (?) if Formating is changed this value should as well. I suggested the np.ma as a way of visualizing the use of mask. np.ma.sum would have taken care of the 0 fill. Commented Mar 12, 2021 at 3:27

1 Answer 1

1

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.])
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way i could modify the output to be between the set boundaries and result in [ 0 7 30 0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.