在 pandas 切片上设置值的正确方法 [英] Correct way to set value on a slice in pandas
问题描述
我有一个pandas数据框:数据.它具有列["name",'A','B']
I have a pandas dataframe: data. it has columns ["name", 'A', 'B']
我想做的(可行的)是:
What I want to do (and works) is:
d2 = data[data['name'] == 'fred'] #This gives me multiple rows
d2['A'] = 0
这会将表行的A列设置为0. 我也做了:
This will set the column A on the fred rows to 0. I've also done:
indexes = d2.index
data['A'][indexes] = 0
但是,两者都给我相同的警告:
However, both give me the same warning:
/Users/brianp/work/cyan/venv/lib/python2.7/site-packages/pandas/core/indexing.py:128: SettingWithCopyWarning:
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
熊猫如何让我做到这一点?
How does pandas WANT me to do this?
推荐答案
这是熊猫的一种非常常见的警告.这意味着您正在写的是复制片,而不是原始数据,因此由于链式分配的混乱,它可能不适用于原始列.请阅读此帖子.它已对此SettingWithCopyWarning
进行了详细讨论.就您而言,我认为您可以尝试
This is a very common warning from pandas. It means you are writing in a copy slice, not the original data so it might not apply to the original columns due to confusing chained assignment. Please read this post. It has detailed discussion on this SettingWithCopyWarning
. In your case I think you can try
data.loc[data['name'] == 'fred', 'A'] = 0
这篇关于在 pandas 切片上设置值的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!