16

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!

2 Answers 2

21

The following will do it:

elevation[elevation > 0] = numpy.NAN

See Indexing with Boolean Arrays in the NumPy tutorial.

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

Comments

3
np.putmask(elevation, elevation > 0, np.nan)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.