Medulla Oblongata
Medulla Oblongata

Reputation: 3973

Python setting range of monotonic values in array to zero

If I have an array of monotonically increasing values, how do I set the end values to zero? For example:

import numpy as np

a = np.array([1.2,2.2,3.1,4.4,8.3,9])
b = 4.5

for i in np.arange(b,max(a)):
    np.put(a,[i],[0])

print(a)

Upvotes: 1

Views: 116

Answers (2)

DSM
DSM

Reputation: 353379

I don't think that it's worth the effort to take advantage of the fact that if it's monotonically increasing you can save yourself many comparisons. Simply write

>>> a = np.array([1.2,2.2,3.1,4.4,8.3,9])
>>> a[a > 4.5] = 0.0
>>> a
array([ 1.2,  2.2,  3.1,  4.4,  0. ,  0. ])

and get on with your day. I suppose you could experiment with something like

>>> a = np.array([1.2,2.2,3.1,4.4, 8.3, 9])
>>> a[np.searchsorted(a, 4.5):] = 0
>>> a
array([ 1.2,  2.2,  3.1,  4.4,  0. ,  0. ])

but you'd have to think through how you want to handle the edge case.

Upvotes: 1

aplassard
aplassard

Reputation: 759

If your input is a list, something like the following should work

a = [1.2,2.2,3.1,4.4,8.3,9]
b = 4.5
a = map(lambda x: x if x <=b else 0.0, a)

If you want to work with numpy objects

a = np.array([1.2,2.2,3.1,4.4,8.3,9])
b = 4.5
a = np.array(map(lambda x: x if x ><=b else 0.0, a.tolist()))

EDIT: this is not the most computationally efficient way to compute this operation, but it should be effective.

Upvotes: 1

Related Questions