从大熊猫的 Fillna 中消除错误

时间:2021-05-02 13:08:33

标签: python pandas error-handling fillna

我尝试用以下方法填充数据框中列的 NA 值:

df1 = data.copy()
df1.columns = data.columns.str.lower()
df2 = df1[['passangerid', 'trip_cost','class']]
df2['class'] = df2['class'].fillna(0)
df2

虽然收到此错误:

<块引用>

:5: SettingWithCopyWarning: 试图在来自 DataFrame 的切片副本上设置值。 尝试使用 .loc[row_indexer,col_indexer] = value 代替

查看注意事项in the documentation

<块引用>

df2['class'] = df2['class'].fillna(0,axis = 0)

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

首先,我建议您遵循警告消息并阅读所提供链接中的注意事项。

您收到此警告(不是错误)是因为您的 df2 是 df1 的一部分,而不是单独的 DataFrame。

为避免收到此警告,您可以使用 .copy() 方法:

df2 = df1[['passangerid', 'trip_cost','class']].copy()