Home > Mobile >  Replace data in an array with numpy
Replace data in an array with numpy

Time:09-27

I am using a digital elevation model as an array, and I want to create a new array with only the pixels below a certain value. I tried using a for loop.

Here is the operation with simpler data :

import numpy as np

array1 = array2 = np.arange(9).reshape(3,3)
array2 = array2.astype("float") #np.nan doesn't work with integers

for row in array2: 
    for item in row:
        if item > 3.0:
            item=np.nan

print(np.array_equal(array1,array2))

The arrays remain equal after the loop is over. Do you know why the values won't be replaced?

CodePudding user response:

You only change item you need insert item in array2, you can use np.where like below:

>>> array1 = np.arange(9).reshape(3,3)
>>> array2 = np.where(array1 > 3, np.nan, array1)
>>> array2
array([[ 0.,  1.,  2.],
       [ 3., nan, nan],
       [nan, nan, nan]])

>>> np.array_equal(array1, array2)
False

CodePudding user response:

Values are not replaced because item is a copy of each array item.

Beside this, using a pure-Python loop is not efficient. Consider vectorizing the code with array2[array2 > 3.0] = np.nan.

  • Related