Pandas 奇怪的 SettingWithCopyWarning 警告

Pandas weird SettingWithCopyWarning warning

有一个只有一列的 DataFrame volume_:

up = df['volume_'].rolling(30).max()
df['up'] = up

导致关于“试图在数据帧的切片副本上设置值”的经典半永久性 SettingWithCopyWarning 警告。这个众所周知的警告表明:

Try using .loc[row_indexer,col_indexer] = value instead

好吧,就照他们说的做吧!

up = df['volume_'].rolling(30).max()
df.loc[:, 'up'] = up

现在,我得到的不是 one SettingWithCopyWarning 警告,而是 two!

site-packages/pandas/core/indexing.py:845: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  self.obj[key] = _infer_fill_value(value)
site-packages/pandas/core/indexing.py:1048: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  self.obj[item_labels[indexer[info_axis]]] = value

本质上,Pandas 是在抱怨我使用 df.loc[:, 'up'] = ... 并建议我改用 df.loc[:, 'up'] = ......

什么是正确的、Pandas 符合此目的的方法?

我知道了。

我在问题中没有说(并且认为不相关)的是我正在构建 df 切片现有的 DataFrame:

df = other_df[['volume_']]

当我这样做时:

df = other_df[['volume_']].copy()

然后一切按顺序回落。

不过,我的结论是,至少可以说,警告信息的措辞更清楚一点可能会有所帮助。