执行熊猫查询时的SettingWithCopyWarning

时间:2020-01-24 14:19:41

标签: python pandas dataframe

我有一个数据框df1,其列名称为“ col1”和“ col2”。我想根据col1中的某些条件更新col2中的值。我执行下面的代码,但出现错误:

SettingWithCopyWarning: 试图在DataFrame的切片副本上设置一个值

请参见文档中的警告:http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

这是我的代码: code

如何消除此警告?

1 个答案:

答案 0 :(得分:1)

您正在使用链式索引:

df["col2"].iloc[query_index]

这实际上是要提前告知这两个中的哪一个返回基础数据帧的副本或视图。因此,警告。

您的问题可以通过内置的矢量化函数来解决:

df["col2"] = df["col2"].where(~df["col1"].isin(list1), df["col1"])

col2中的行不在list1中时,请保留其原始值,否则请使用col1中的值。

相关问题