实施列比较时的 SettingWithCopyWarning [重复]
Posted
技术标签:
【中文标题】实施列比较时的 SettingWithCopyWarning [重复]【英文标题】:SettingWithCopyWarning when implementing column comparison [duplicate] 【发布时间】:2019-01-18 15:47:36 【问题描述】:我正在使用来自Pandas SettingWithCopyWarning 的答案 在我的脚本中,但它返回了“SettingWithCopyWarning”,我可以知道我应该如何解决它吗?
attemped1: dff['changed'] = dff.col1.ne(dff.col1.shift(1)) attemped2: dff.loc[:, 'changed] = dff.col1.ne(dff.col1.shift(1))
【问题讨论】:
【参考方案1】:您的代码是正确的,问题出在上面的某行。
我猜你过滤了你的DataFrame
,解决方案是添加copy
:
dff = df[df['col2'] == 1].copy()
dff['changed'] = dff.col1.ne(dff.col1.shift(1))
如果您稍后修改 dff
中的值,您会发现修改不会传播回原始数据 (df
),并且 Pandas 会发出警告。
【讨论】:
如果没有 copy() 是否会修改原始数据框?我在下面的测试用例中看不到效果? df = pd.DataFrame('col1':['A', 'B', 'C'], 'col2':[111,222,333], 'col3':['aaa', 'bbb', 'aaa'] ) dff = df[df.col3 == 'aaa'] dff.loc[0, 'col3'] = 'zzz' @user466130 - 稍等。 @user466130 - 不,原始 df 没有修改。这是警告,因为可能chaining indexing。另请查看this 以获取示例数据的解释。 @user466130 - 还有另一种关闭此警告的方法,pd.options.mode.chained_assignment = None
以上是关于实施列比较时的 SettingWithCopyWarning [重复]的主要内容,如果未能解决你的问题,请参考以下文章