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!
There are three ways to replace an item in a Python list. You can use list indexing or a for loop to replace an item. If you want to create a new list based on an existing list and make a change, you can use a list comprehension. You may decide that you want to change a value in a list.
Fancy indexing is conceptually simple: it means passing an array of indices to access multiple array elements at once. For example, consider the following array: import numpy as np rand = np. random. RandomState(42) x = rand.
In NumPy, to replace missing values NaN ( np. nan ) in ndarray with other numbers, use np. nan_to_num() or np. isnan() .
The following will do it:
elevation[elevation > 0] = numpy.NAN
See Indexing with Boolean Arrays in the NumPy tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With