对 pandas 数据帧的切片执行操作的正确方法?

Correct way to perform operation on a slice of a pandas dataframe?

提问人:peter_wx 提问时间:1/27/2023 更新时间:1/27/2023 访问量:95

问:

我正在尝试编写一个函数来对任何 pandas 数据帧进行去季节性化。这总是有效的,但我仍然收到“SettingWithCopyWarning: 正在尝试在 DataFrame 中的切片副本上设置值” 这不是设置值的正确方法吗?

def deseasonalize(df):
    # Function to deseasonalize any pandas dataframe
    df.loc[df.index.month==1]=df.loc[df.index.month==1]-df.loc[df.index.month==1].mean()
    df.loc[df.index.month==2]=df.loc[df.index.month==2]-df.loc[df.index.month==2].mean()
    df.loc[df.index.month==3]=df.loc[df.index.month==3]-df.loc[df.index.month==3].mean()
    df.loc[df.index.month==4]=df.loc[df.index.month==4]-df.loc[df.index.month==4].mean()
    df.loc[df.index.month==5]=df.loc[df.index.month==5]-df.loc[df.index.month==5].mean()
    df.loc[df.index.month==6]=df.loc[df.index.month==6]-df.loc[df.index.month==6].mean()
    df.loc[df.index.month==7]=df.loc[df.index.month==7]-df.loc[df.index.month==7].mean()
    df.loc[df.index.month==8]=df.loc[df.index.month==8]-df.loc[df.index.month==8].mean()
    df.loc[df.index.month==9]=df.loc[df.index.month==9]-df.loc[df.index.month==9].mean()
    df.loc[df.index.month==10]=df.loc[df.index.month==10]-df.loc[df.index.month==10].mean()
    df.loc[df.index.month==11]=df.loc[df.index.month==11]-df.loc[df.index.month==11].mean()
    df.loc[df.index.month==12]=df.loc[df.index.month==12]-df.loc[df.index.month==12].mean()
    return df
python pandas pandas-settingwithcopy-warning

评论

2赞 Amin S 1/27/2023
这回答了你的问题吗?如何处理 Pandas 中的 SettingWithCopyWarning
0赞 Florian Fasmeyer 1/27/2023
我认为在函数的开头添加可能会解决这个问题。在函数中,您希望修改参数的副本,而不是原始参数。仅当您返回用户应选择是否覆盖它的结果时,才会这样做。df = df.copy()df = deseasonalize(df)
1赞 Derek O 1/27/2023
我知道你的问题是关于 的,但你的方法有点反模式,因为你正在对月份进行硬编码——而且使用 . 重复切片你的 df 也是低效的。相反,您可以使用内置方法(例如针对数据帧优化的 and)来完成相同的任务 - 请参阅此问答,了解一个非常优雅(且高效)的解决方案SettingWithCopyWarning.locgroupbytransform

答: 暂无答案