Reut
Reut

Reputation: 1592

Change 0 values to nan values in numpy array changes everything to nan

I have numpy array with the shape of (1212,2117). The array contains pixels with value 0 or values that are rgeater than 0 , looks like this: enter image description here

I want to give the 0 pixels value of no data. I have tried to do it this way:

arr=arr.astype('float')
arr[arr==0]=np.nan

It seems like the result is chart that is all NaN.with one little square:

plt.imshow(test)

enter image description here

However it seems like all the values were changes, as if I check what is the max or min value of this array I get nan:

test.max()
>>>nan

test.min()
>>>nan

I would like to understand why I get this result and how can I correctly give no data values for pixels with value of 0.

Upvotes: 1

Views: 929

Answers (2)

Guy
Guy

Reputation: 51009

You have the reason and solution in the docs (Notes section).

NaN values are propagated, that is if at least one item is NaN, the corresponding max value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmax.

np.nanmax(arr)
# and
np.nanmin(arr))

Should give the expected result.

Upvotes: 1

sub2nullexception
sub2nullexception

Reputation: 118

Make a list

Iterate through every pixel, check if it is a nan, then append 0, if not then append the number.

np.array(your array)

Although it is unpythonic, it may get the job done.

Upvotes: 0

Related Questions