numpy将特定值更改为null会出现错误“ValueError:无法将浮点NaN转换为整数”

wnavrhmk  于 2023-04-21  发布在  其他
关注(0)|答案(3)|浏览(133)

我有一个形状为(1,5,10)的numpy数组。

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)

我想把所有的-5都换成np.nan值。为了做到这一点,我写了以下代码:

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

但这给了我一个错误:
ValueError:无法将float NaN转换为整数
为什么我会得到这个错误?我如何将值替换为nan?

bvjxkvbb

bvjxkvbb1#

你只需要先将它转换为float

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

ig9co6j12#

你可以把out_image当作一个pandas.Dataframe来做。相反,你可以像这样使用numpy.where方法:

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

wz1wpwve3#

I was also facing same issue ,when I was storing my Data into BigInt column and to counter the issue to store Nan/Null/None into int/BigInt datatype I have used below approach.

df['column_name'] = df['column_name'].convert_dtypes()
df['column_name'] = df['column_name'].astype('Int64')

using first line code I have converted all values into float and then with below 
code I have converted back everything into Int64

you can directly jump to second part for me i have to do some other changes into my column values that's why I have used convert_dtypes()

相关问题