df.loc导致SettingWithCopyWarning警告消息 [英] df.loc causes a SettingWithCopyWarning warning message
问题描述
我的代码的以下行会引发警告:
The following line of my code causes a warning :
import pandas as pd
s = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
s.loc[-1] = [5,np.nan,np.nan,6]
grouped = s.groupby(['A'])
for key_m, group_m in grouped:
group_m.loc[-1] = [10,np.nan,np.nan,10]
C:\Anaconda3\lib\site-packages\ipykernel\__main__.py:10: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
根据文档这是推荐的方法,那么发生了什么?
According to the documentation this is the recommended way of doing, so what is happening ?
感谢您的帮助.
推荐答案
文档有些混乱.
您的dataframe
是另一个dataframe
的副本.您可以通过运行bool(df.is_copy)
来验证这一点.由于您正在尝试分配给该副本,因此您将收到警告.
Your dataframe
is a copy of another dataframe
. You can verify this by running bool(df.is_copy)
You are getting the warning because you are trying to assign to this copy.
警告/文档首先告诉您应该如何构造df
.现在它已经是副本了,不是您应该如何分配它.
The warning/documentation is telling you how you should have constructed df
in the first place. Not how you should assign to it now that it is a copy.
df = some_other_df[cols]
将使df
成为some_other_df
的副本.警告建议改为这样做
will make df
a copy of some_other_df
. The warning suggests doing this instead
df = some_other_df.loc[:, [cols]]
现在已完成,如果您选择忽略此警告,则可以
Now that it is done, if you choose to ignore this warning, you could
df = df.copy()
或
df.is_copy = None
这篇关于df.loc导致SettingWithCopyWarning警告消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!