pandas 如何修改熊猫数据框的一个“单元格”中的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26657378/
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
How to modify a value in one "cell" of a pandas data frame?
提问by Roman
I have a very simple problem. I would like to change a value in a given column of a given row of a pandas data frame. I try to do it in the following way:
我有一个非常简单的问题。我想更改 Pandas 数据框给定行的给定列中的值。我尝试通过以下方式做到这一点:
df['column3'].loc[this_date] = val
As a result I get the following warning:
结果我收到以下警告:
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
My interpretation of this warning is that by using columns name ('column3') and locI do not really access (refer to) the desired cell of the data frame. Instead, I create an object which is a copy of the "cell" object and then I try to change the value associated with this "copy-object".
我对这个警告的解释是,通过使用列名 ( 'column3'),loc我并没有真正访问(参考)数据框的所需单元格。相反,我创建了一个对象,它是“单元格”对象的副本,然后我尝试更改与此“复制对象”关联的值。
What I do not understand is that it seems to work. In spite on the fact that pandas writes me that I try to modify the copy, I do modify the original data frame.
我不明白的是它似乎有效。尽管Pandas写信给我说我尝试修改副本,但我确实修改了原始数据框。
My question is how to make sure that I am really doing what I would like to do and how to do it in a "correct" way so that the pandas does not complain?
我的问题是如何确保我真的在做我想做的事情以及如何以“正确”的方式做到这一点,以便Pandas不会抱怨?
回答by Yang
The reason of getting the warning is that dfitself is a copy of some other dataframe object. I guess that you have some original dataframe df_originand you get dffrom df_originby some operation such as slicing. So dfis a copy of df_origin. Then you try to set some value to dfand the warning raises to tell you that this would not change the value in the original dataframe df_origin.
One solution is to use a single variable to point to the dataframe object before and after slicing if you don't care for df_origin. Otherwise you can suppress the warning by pd.set_option('mode.chained_assignment', None)
收到警告的原因是它df本身是某个其他数据帧对象的副本。我想,你有一些原始的数据帧df_origin,你会得到df从df_origin一些操作,如切片。所以,df是的副本df_origin。然后,您尝试将某个值设置为 ,df并且会出现警告以告诉您这不会更改原始数据帧中的值df_origin。如果您不关心 df_origin,一种解决方案是在切片前后使用单个变量指向数据帧对象。否则,您可以通过以下方式抑制警告pd.set_option('mode.chained_assignment', None)
Your way of setting value is fine, along with the following ones:
您设置值的方式很好,还有以下几种:
df.ix[this_date, 'column3'] = val
df.loc[this_date, 'column3'] = val
df.at[this_date, 'column3'] = val

