vpap
vpap

Reputation: 1547

Numpy mask array on both sides

Assume a numpy array x. How can I do x[x>value] = max(value1, x[x>value])?

In words, if element x[i] > value, then x[i] = max(value1, x[i]).

Thanks.

EDIT Using numpy.maximum instead of numpy.max solved the problem. When I had numpy.max I was getting the error message TypeError: only integer scalar arrays can be converted to a scalar index

Upvotes: 1

Views: 77

Answers (2)

Ehsan
Ehsan

Reputation: 12397

You can use np.where and single combined condition:

np.where((x>value)&(x<value1), value1, x)

or equivalently:

x[(x>value) & (x<value1)] = value1

Example:

x = np.arange(20).reshape(4,5)
value=5
value1=10
#output:
array([[ 0,  1,  2,  3,  4],
       [ 5, 10, 10, 10, 10],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

Upvotes: 1

hpaulj
hpaulj

Reputation: 231335

Make an array:

In [361]: x = np.random.randint(0,10,10)
In [362]: x
Out[362]: array([7, 8, 4, 8, 1, 2, 6, 6, 3, 9])

Identify the values to be replaced:

In [363]: mask = x>5
In [364]: mask
Out[364]: 
array([ True,  True, False,  True, False, False,  True,  True, False,
        True])
In [365]: x[mask]
Out[365]: array([7, 8, 8, 6, 6, 9])

The replacement values:

In [368]: np.maximum(7, x[mask])
Out[368]: array([7, 8, 8, 7, 7, 9])

As long as the both sides have the same number of terms (shape actually):

In [369]: x[mask] = np.maximum(7, x[mask])
In [370]: x
Out[370]: array([7, 8, 4, 8, 1, 2, 7, 7, 3, 9])

Since this is actually just changing the values between 5 and 7, we could use:

In [378]: x = np.array([7, 8, 4, 8, 1, 2, 6, 6, 3, 9])
In [379]: mask = (x>5) & (x<7)
In [380]: mask
Out[380]: 
array([False, False, False, False, False, False,  True,  True, False,
       False])
In [381]: x[mask]
Out[381]: array([6, 6])
In [382]: x[mask] = 7

Upvotes: 1

Related Questions