Mc Missile
Mc Missile

Reputation: 735

Python numpy mask a range of values

I have a 2D array called img of size 100x100. I am trying to mask all values bigger than -100 and lesser than 100 as folows.

img = np.ma.masked_where(-100 < img < 100, img)

However, the above gives me an error saying

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Thanks.

Upvotes: 0

Views: 8518

Answers (2)

G M
G M

Reputation: 22459

You can also use masked inside, for instance we can mask the value between the 2 and 5 range:

import numpy as np 
from numpy import ma 
img = np.arange(9).reshape(3,3)
imgm = ma.masked_inside(img,2,5)

Upvotes: 1

MSeifert
MSeifert

Reputation: 152647

You cannot use the chained comparisons with NumPy arrays because they use Pythons and under the hood.

You have to use & or the function equivalents numpy.logical_and or numpy.bitwise_and.

For example:

np.ma.masked_where((-100 < img) & (img < 100), img)

Upvotes: 0

Related Questions