Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 875
Kurt Schwehr Avatar asked Nov 03 '11 11:11

Kurt Schwehr


People also ask

How do you replace an array value in Python?

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.

What is NumPy fancy indexing?

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.

How do I replace missing values in NumPy?

In NumPy, to replace missing values NaN ( np. nan ) in ndarray with other numbers, use np. nan_to_num() or np. isnan() .


1 Answers

The following will do it:

elevation[elevation > 0] = numpy.NAN

See Indexing with Boolean Arrays in the NumPy tutorial.

like image 134
NPE Avatar answered Oct 21 '22 14:10

NPE