2

Here's my array:

import numpy as np
a = np.array([0, 5.0, 0, 5.0, 5.0])

Is it possible to use numpy.where in some way to add a value x to all those entires in a that are less than l?

So something like:

a = a[np.where(a < 5).add(2.5)]

Should return:

array([2.5, 5.0, 2.5, 5.0, 5.0])

5 Answers 5

5
a = np.array([0., 5., 0., 5., 5.])
a[np.where(a < 5)] += 2.5

in case you really want to use where or just

a[a < 5] += 2.5

which I usually use for these kind of operations.

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

Comments

4

You could use np.where to create the array of additions and then simply add to a -

a + np.where(a < l, 2.5,0)

Sample run -

In [16]: a = np.array([1, 5, 4, 5, 5])

In [17]: l = 5

In [18]: a + np.where(a < l, 2.5,0)
Out[18]: array([ 3.5,  5. ,  6.5,  5. ,  5. ])

1 Comment

Just wanted to highlight that this is the only answers (except mine :-)) that works if the dtypes are too different (int += float) to allow in-place addition.
4

Given that you probably need to change the dtype (from int to float) you need to create a new array. A simple way without explicit .astype or np.where calls is multiplication with a mask:

>>> b = a + (a < 5) * 2.5
>>> b
array([ 2.5,  5. ,  2.5,  5. ,  5. ])

with np.where this can be changed to a simple expression (using the else-condition, third argument, in where):

>>> a = np.where(a < 5, a + 2.5, a)
>>> a
array([ 2.5,  5. ,  2.5,  5. ,  5. ])

2 Comments

thanks for pointing out the mistake with the type. It should be float.
@AnthonyW That's why we talk of representative sample when posting questions :)
1
a += np.where(a < 1, 2.5, 0)

where will return the second argument wherever the condition (first argument) is satisfied and the third argument otherwise.

Comments

1

You can use a "masked array" as an index. Boolean operations, such as a < 1 return such an array.

>>> a<1
array([False, False, False, False, False], dtype=bool)

you can use it as

>>> a[a<1] += 1

The a<1 part selects only the items in a that match the condition. You can operate on this part only then.

If you want to keep a trace of your selection, you can proceed in two steps.

>>> mask = a>1
>>> a[mask] += 1

Also, you can count the items matching the conditions:

>>> print np.sum(mask)

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.