Python 使用loc时发出警告

Python 使用loc时发出警告,python,pandas,group-by,Python,Pandas,Group By,我有一个代码示例,它应该使用group by将一个数据帧拆分为更小的数据帧,并在“num”列中的数字为偶数时修改更小的数据帧: import pandas as pd df = pd.DataFrame({ 'id1': [1]*5+[2]*5, 'num': range(11, 21), 'x': range(10) }) print df for id1, grouped_df in df.groupby('id1'): grouped_df.loc[gr

我有一个代码示例,它应该使用group by将一个数据帧拆分为更小的数据帧,并在“num”列中的数字为偶数时修改更小的数据帧:

import pandas as pd

df = pd.DataFrame({
    'id1': [1]*5+[2]*5,
    'num': range(11, 21),
    'x': range(10)

})
print df
for id1, grouped_df in df.groupby('id1'):
    grouped_df.loc[grouped_df['num'] % 2 == 0, 'num'] = 'even'
    print grouped_df

print df
但是,当我运行此代码时,会遇到警告:

/usr/local/lib/python2.7/dist-packages/pandas/core/index.py:537: SettingWithCopyWarning:正在尝试在副本上设置值 从数据帧切片。尝试使用.loc[行索引器、列索引器]= 取而代之的是价值观

请参阅文档中的注意事项:

当在“真实”数据上运行时,代码速度非常慢

据我所知,此警告建议使用
loc
,但我已经在使用它了! pandas是否将group by返回的数据帧视为切片?如何消除此警告并确保预期行为?

使用:


警告不一定与程序性能有关。警告就是警告,通常是误报。您可以尝试进行基准测试,看看什么需要时间dataframe@MaxSegal-好的,那么解决方案完全改变了。
for id1, grouped_df in df.groupby('id1'):
    grouped_df = grouped_df.copy()
    grouped_df.loc[grouped_df['num'] % 2 == 0, 'x'] = 'even'
    print (grouped_df)

   id1  num     x
0    1   11     0
1    1   12  even
2    1   13     2
3    1   14  even
4    1   15     4
   id1  num     x
5    2   16  even
6    2   17     6
7    2   18  even
8    2   19     8
9    2   20  even