提问人:peter_wx 提问时间:1/27/2023 更新时间:1/27/2023 访问量:95
对 pandas 数据帧的切片执行操作的正确方法?
Correct way to perform operation on a slice of a pandas dataframe?
问:
我正在尝试编写一个函数来对任何 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
答: 暂无答案
上一个:避免引发带有复制警告的设置
评论
df = df.copy()
df = deseasonalize(df)
SettingWithCopyWarning
.loc
groupby
transform