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!
Answers:
The following will do it:
elevation[elevation > 0] = numpy.NAN
See Indexing with Boolean Arrays in the NumPy tutorial.
np.putmask(elevation, elevation > 0, np.nan)
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!
The following will do it:
elevation[elevation > 0] = numpy.NAN
See Indexing with Boolean Arrays in the NumPy tutorial.
np.putmask(elevation, elevation > 0, np.nan)