试图在DataFrame警告的切片副本上设置一个值 [英] A value is trying to be set on a copy of a slice from a DataFrame Warning
本文介绍了试图在DataFrame警告的切片副本上设置一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不确定在更新为消息所建议的.loc方法后,为什么仍然收到警告吗?这是假警报吗?
Not sure why I still get the warning after I updated to .loc method suggested by the message? Is it a false alarm?
eG.loc[:,'wt']=eG.groupby(['date','BB'])['m'].transform(weightFunction)
试图在DataFrame的切片副本上设置一个值
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
if __name__ == '__main__':
推荐答案
我想您的eG
DF是另一个DF的副本...
I guess your eG
DF is a copy of another DF...
这是一个小演示:
In [69]: df = pd.DataFrame(np.random.randint(0, 5, (10, 3)), columns=list('abc'))
In [70]: cp = df[df.a > 0]
In [71]: cp.loc[:, 'c'] = cp.groupby('a').b.transform('sum')
c:\envs\py35\lib\site-packages\pandas\core\indexing.py:549: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self.obj[item_labels[indexer[info_axis]]] = value
解决方法:
In [72]: cp = df[df.a > 0].copy()
In [73]: cp.loc[:, 'c'] = cp.groupby('a').b.transform('sum')
或者,如果您不需要原始DF,则可以节省内存:
Or if you don't need original DF you can save memory:
In [74]: df = df[df.a > 0]
In [75]: df.loc[:, 'c'] = df.groupby('a').b.transform('sum')
这篇关于试图在DataFrame警告的切片副本上设置一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文