Search code examples
pythonnumpymask

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.


Solution

  • 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)