Home > Back-end >  numpy change specific value to null gives error "ValueError: cannot convert float NaN to intege
numpy change specific value to null gives error "ValueError: cannot convert float NaN to intege

Time:04-12

I have numpy array with the shape of (1,5,10).

array([[[ -5,  -5,  -5,  -5, 120, 116, 118, 118,  -5,  -5],
        [ -5,  -5, 126, 127, 125, 118, 118, 123,  -5,  -5],
        [ -5, 121, 125, 118, 115, 115, 121, 121, 114, 127],
        [112, 118, 108, 111, 110, 112, 104, 102, 103,  -5],
        [105, 108, 107,  -5,  -5,  -5,  -5,  -5,  -5,  -5]]], dtype=int16)

I would like to change all the -5 into np.nan value. In order to do that I have written this code:

out_image[out_image == (-5)] = np.nan

but that gives me an error:

ValueError: cannot convert float NaN to integer

Why do I get this error? and how can I replace the values into nan?

CodePudding user response:

You're doing it as out_image were a pandas.Dataframe. Instead you can use numpy.where method like this:

np.where(out_image == -5, np.NaN, out_image)

CodePudding user response:

You just need to convert it to float first.

out_image = out_image.astype('float')
out_image[out_image== -5] = np.NAN
  • Related