1

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?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

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.