1

Many topics exist to sum an array based on another array indexes but i couldn't find what i am looking for.

I have an array [1,1,1,1,2,3,3,0,0,2,4] and i would like to get indexes by which the sum until now is greater or equal to 4. So I would get:

[3, 5, 9, 10] because:

Sum([1,1,1,1]) >= 4

Sum([2,3]) >= 4

Sum([3,0,0,2]) >= 4

I need the indexes of the element at which the sum value is fulfilled.

I could do it with a loop but i am looking for doing it efficiently with numpy or the like.

6
  • 1
    Could there be negative values? Commented Nov 8, 2017 at 10:51
  • 3
    What if the sum for the current group never reaches exactly 4, and the next item takes it over 4? Are the items guaranteed to be integers, or could there be floats? Commented Nov 8, 2017 at 10:52
  • Right, i updated the question, i was not clear enough, i need the slicing based on the first index where the cumsum passed the sum value i am looking for. Commented Nov 8, 2017 at 11:08
  • Think you should update with a more relevant sample. Maybe like : [1, 1, 3, 1, 2, 2, 3, 0, 0, 1, 4], so that the answers won't fall prey to the simplistic sample. Commented Nov 8, 2017 at 11:11
  • @Divakar : thx. I did already in my last update. Commented Nov 8, 2017 at 11:14

2 Answers 2

2

You can use np.where in conjunction with np.cumsum:

import numpy as np

li = [1,1,1,1,2,2,3,0,0,1,4]

print(np.where(np.cumsum(li) % 4 == 0))
# (array([ 3,  5,  9, 10], dtype=int32),)

The gotcha here of course is that it will also find indexes where the sum is 8, 12, 16, 20 etc.

Unfortunately I'm not sure there is way to "reset" cumsum, if there was you could do something like np.where(np.cumsum(li) - 4 == 0) (but currently it will only return 3).

However, you could slice the array every time cumsum reaches 4, but you didn't want to use loops.

Sign up to request clarification or add additional context in comments.

1 Comment

What if it's [1, 1, 3, 1, 2, 2, 3, 0, 0, 1, 4]? As an example of what PM 2Ring commented about.
1
array =[1,1,1,1,2,2,3,0,0,1,4]
print(np.where(np.cumsum(array)%4==0))  

now, if you change your array then you can check whenever sum goes beyond 4 then u can take the last index and proceed further.

Comments

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.