How to limit np array by sum of its elements

Viewed 81

I need to somehow limit my array by sum of its elements. So, I suppose to do something like

l = [1, 3, 4, 5, 2, 7]
if sum(l) >= 10:
    ans = [1, 3, 4, 0, 0, 0]

In general, I want to generate some trains, which have 5 or 10 minutes difference (p_i = 1/2)

a = np.random.choice([5, 10], (10**4, n)) -- like this.

But the sum of elements must be <= 600 and I have to use maximum of numpy abilities.

1 Answers

You can use np.cumsum together with np.argmax in this way:

import numpy as np

MAX_SUM = 10

arr = np.array([[1, 3, 4, 5, 2, 7]])
arr[np.argmax(np.cumsum(arr) >= MAX_SUM):] = 0

print(arr)
# array([1, 3, 4, 0, 0, 0])
Related