如何避免“试图在DataFrame的切片副本上设置值"? [英] How to avoid 'A value is trying to be set on a copy of a slice from a DataFrame'?
本文介绍了如何避免“试图在DataFrame的切片副本上设置值"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,df_original
:
a b
0 10 5
1 12 6
2 14 1
现在,我想创建一个包含所有行在c > 5
的新数据框,然后在此新数据框上设置新的列值:
Now I want to make a new dataframe containing all rows where c > 5
, and then set a new column value on this new dataframe:
df = df_original[df_original['b'] > 5]
df['c'] = df['a'] / df['b']
但是我得到警告:
/Library/Python/2.7/site-packages/ipykernel/__main__.py:25: 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 the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
如果c
不返回原始数据框,我会感到非常高兴.但是我应该如何正确执行操作并避免出现警告?
I'm quite happy if c
doesn't make its way back to the original dataframe. But how should I do this properly and avoid warnings?
推荐答案
Take a copy
to avoid the warning:
In [118]:
df1 = df[df['b'] > 5].copy()
df1['c'] = df1['a'] / df1['b']
df1
Out[118]:
a b c
1 12 6 2.0
这避免了通话中的歧义
这篇关于如何避免“试图在DataFrame的切片副本上设置值"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文