Python 在 Pandas 中的切片上设置值的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37841525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way to set value on a slice in pandas
提问by Brian Postow
I have a pandas dataframe: data. it has columns ["name", 'A', 'B']
我有一个熊猫数据框:数据。它有列 ["name", 'A', 'B']
What I want to do (and works) is:
我想做(和工作)的是:
d2 = data[data['name'] == 'fred'] #This gives me multiple rows
d2['A'] = 0
This will set the column A on the fred rows to 0. I've also done:
这会将 fred 行上的列 A 设置为 0。我也做了:
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?
大熊猫要我怎么做?
回答by Andreas Hsieh
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
这是熊猫的一个非常常见的警告。这意味着您正在写入副本切片,而不是原始数据,因此由于混乱的链式分配,它可能不适用于原始列。请阅读这篇文章。它对此有详细的讨论SettingWithCopyWarning
。在你的情况下,我认为你可以尝试
data.loc[data['name'] == 'fred', 'A'] = 0