Fast in-place replacement of some values in a numpy array

Question:

There has got to be a faster way to do in place replacement of values, right? I’ve got a 2D array representing a grid of elevations/bathymetry. I want to replace anything over 0 with NAN and this way is super slow:

for x in range(elevation.shape[0]):
    for y in range(elevation.shape[1]):
        if elevation[x,y] > 0:
            elevation[x,y] = numpy.NAN

It seems like that has so be a much better way!

Asked By: Kurt Schwehr

||

Answers:

The following will do it:

elevation[elevation > 0] = numpy.NAN

See Indexing with Boolean Arrays in the NumPy tutorial.

Answered By: NPE
np.putmask(elevation, elevation > 0, np.nan)
Answered By: eumiro
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.