3

拥有一列的 DataFrame volume_

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

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

尝试改用 .loc[row_indexer,col_indexer] = value

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

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

现在,我得到了两个,而不是一个SettingWithCopyWarning 警告!

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 的方法是什么?

4

1 回答 1

1

我得到了它。

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

df = other_df[['volume_']]

当我这样做时:

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

然后一切都恢复正常。

尽管如此,我的结论是,至少可以说,如果措辞更清楚一些,警告信息可能会受益。

于 2020-07-02T17:49:53.023 回答