执行panda操作时发出警告-试图在DataFrame的切片副本上设置值



我正在学习熊猫,并试图做以下事情。

我认为这不是重复的问题,这就是为什么我在这里张贴它。

我想通过dataframe中可用的特定动物的平均值来添加列Average Speed。我可以这样做,可能不是正确的方式。但最后我得到了警告。

d = {'Animal': ['Parrot','Falcon','Parrot','Falcon'], 'MaxSpeed' : [56,360,58,380 ]}
adf = pd.DataFrame(d)
grp_spd = adf.groupby(by=['Animal']).mean()
adf.insert(column='Average Speed',loc=2, value="")
for x,y in adf.iterrows():
print(x)
print(y.MaxSpeed)
print(grp_spd.loc[y.Animal].MaxSpeed )
adf['Average Speed'][x] = grp_spd.loc[y.Animal].MaxSpeed
#adf.insert(2, 'Average Speed', grp_spd.loc[y.Animal].MaxSpeed)
adf

我收到以下警告信息

试图在DataFrame 的切片副本上设置值

请参阅文档中的注意事项:https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copyadf['平均速度'][x]=grp_spd.loc[y.Animal].MaxSpeed

有人能告诉我如何消除此警告以及正确的方法吗?

原因是在执行adf['Average Speed'][x] = value时,不能保证是否访问了视图或引用了对象。在视图上设置值有一种风险,即当视图对象被清除时,更改将丢失。您可以在此处阅读更多详细信息。

您可以将源代码修改为:

d = {'Animal': ['Parrot','Falcon','Parrot','Falcon'], 'MaxSpeed' : [56,360,58,380 ]}
adf = pd.DataFrame(d)
adf["Average Speed"] = adf.groupby("Animal")["MaxSpeed"].transform("mean")
Animal  MaxSpeed  Average Speed
0  Parrot        56           57.0
1  Falcon       360          370.0
2  Parrot        58           57.0
3  Falcon       380          370.0

最新更新