在pandas中设置切片值的正确方法[重复]

时间:2022-10-22 11:33:50

This question already has an answer here:

这个问题在这里已有答案:

I have a pandas dataframe: data. it has columns ["name", 'A', 'B']

我有一个pandas数据帧:数据。它有列[“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?

大熊猫是怎么想让我这样做的?

1 个解决方案

#1


38  

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

#1


38  

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