我想用“0”替换 NaN 值但不能用下面的代码

I want to replace NaN values with "0" but not able to with the below code

我正在尝试使用以下代码将 NaN 值替换为“0”,它没有给出任何错误,但数据帧也没有变化,你能告诉我我的错误在哪里吗?

df2 = df_num.iloc[:,[8,9,10,11,12,13,14,15,16]]
df2.replace(to_replace ="NaN",value =0, inplace=True)
df2

[the image to my dataframe output is here][1]


[1]: https://i.stack.imgur.com/LamrH.png

在您的代码中,您传递了 to_replace="NaN"

请注意,您实际上向此处传递了一个仅包含这 3 个字母的 字符串

Pandas中你可以传递np.nan,但只能作为要分配的值 到 DataFrame 中的单元格。 Numpy 数组也是如此。

你不能通过to_replace=np.nan,因为比较规则是 np.nan NOT 等于另一个 np.nan.

可能的解决方案之一是 运行:

df2 = df2.where(~df2.isna(), 0)

其他更简单的解决方案,如 richardec 所建议的,是使用 fillna, 但参数应该是 0(零)而不是“o”(一个字符):

df2 = df2.fillna(0)