4

So I have a 2D numpy array (256,256), containing values between 0 and 10, which is essentially an image. I need to remove the 0 values and set them to NaN so that I can plot the array using a specific library (APLpy). However whenever I try and change all of the 0 values, some of the other values get altered, in some cases to 100 times their original value (no idea why).

The code I'm using is:

for index, value in np.ndenumerate(tex_data):
    if value == 0:
        tex_data[index] = 'NaN'

where tex_data is the data array from which I need to remove the zeros. Unfortunately I can't just use a mask for the values I don't need, as APLpy wont except masked arrays as far as I can tell.

Is there anyway I can set the 0 values to NaN without changing the other values in the array?

Sam Billington
  • 299
  • 1
  • 4
  • 11

2 Answers2

5

Use fancy-indexing. Like this:

tex_data[tex_data==0] = np.nan

I don't know why your original code was failing. It looks correct to me, although terribly inefficient.

wim
  • 338,267
  • 99
  • 616
  • 750
0

Using float rules,

tex_data/tex_data*tex_data

make the job here also.

B. M.
  • 18,243
  • 2
  • 35
  • 54