SettingWithCopyWarning:试图在复制数据的切片副本上设置值

xiaoxingxing python 437

原文标题SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a copied data

我知道网络上有很多关于这个特定场景的问题(和答案),但我仍然无法理解在这种情况下是什么原因造成的将被修改

执行此代码时

df = raw.copy() # making a copy of dataframe raw
df['new col'] = ''
for i in range(len(df)):
    df['new col'].loc[i] = 'some thing'

我收到了这个警告

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  self._setitem_single_block(indexer, value, name)

警告是否指的是复制数据帧df(而不是原始数据帧raw)上的更改?处理这种不必要的警告的最佳方法是什么(在这种情况下,我故意想要对复制的数据帧进行更改)

原文链接:https://stackoverflow.com//questions/71686037/settingwithcopywarning-a-value-is-trying-to-be-set-on-a-copy-of-a-slice-from-a

回复

我来回复
  • aaossa的头像
    aaossa 评论

    该警告似乎是指您的 for 循环中的操作。试试这个:

    df[i, 'new col'] = 'some thing'
    

    该语句具有预期的效果:它更改了数据帧中的值,但它直接对数据帧进行操作。当您拆分操作(df['new col'].loc[i])时,您正在对视图(df['new col'])进行操作,这就是警告的原因。

    2年前 0条评论