Search code examples
pythonnumpynanmask

numpy change specific value to null gives error "ValueError: cannot convert float NaN to integer"


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?


Solution

  • You just need to convert it to float first.

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