无法绕过 Pandas 系列 SettingWithCopyWarning

Can't get around Pandas Series SettingWithCopyWarning

我想获取 Series 并对其进行更改,我希望稍后在 DataFrame 中反映出来。但是,如果没有 SettingWithCopyWarning,我无法理解该怎么做。这是误报还是我做错了什么?

df = pd.DataFrame([[1,2,3],[4,5,6]], columns=list('abc'))
df['d'] = df['a'].diff()
d = df.loc[:, 'd']
d.loc[d>0] *= 3

我已经阅读了文档(并且 是的,我在询问之前确实阅读了 this question 但它只处理 DataFrames 而不是 Series),但是'不知道如何解决这个问题。我不想禁用警告,因为我有代码,我不想无意中犯这种类型的错误。

I'd like to fetch a Series and make changes to it, which I'd like reflected in the DataFrame later on.

在这种情况下,您应该暂时禁用此警告并像现在一样继续。使用 .copy() 将意味着您原来的 df 将因 d.

的更改而未修改
with pd.option_context('mode.chained_assignment', None):
    df = pd.DataFrame([[1,2,3],[4,5,6]], columns=list('abc'))
    df['d'] = df['a'].diff()
    d = df.loc[:, 'd']
    d.loc[d>0] *= 3

# Code you run outside of `with` will maintain your original setting:
# pd.get_option('chained_assignment')

option_context 是上下文管理器,这意味着它可以与 with 一起使用,并且该选项仅适用于块内的代码。

阅读更多:pandas > Getting & Setting Options