Pandas 映射到一个新列 SettingWithCopyWarning
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42105859/
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
Pandas map to a new column, SettingWithCopyWarning
提问by Ik-Hwan Kim
In pandas data frame, I'm trying to map df['old_column'], apply user defined function ffor each row and create a new column.
在Pandas数据框中,我试图映射 df['old_column'],为每一行应用用户定义的函数f并创建一个新列。
df['new_column'] = df['old_column'].map(lambda x: f(x))
This will give out "SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame." error.
这将给出“SettingWithCopyWarning:一个值正试图在来自 DataFrame 的切片的副本上设置。” 错误。
I tried the following:
我尝试了以下方法:
df.loc[:, 'new_column'] = df['old_column'].map(lambda x: f(x))
which doesn't help. What can I do?
这没有帮助。我能做什么?
回答by Aleksey Bilogur
A SettingWithCopy
warning is raised for certain operations in pandas
which may not have the expected result because they may be acting on copies rather than the original datasets. Unfortunately there is no easy way for pandas itselfto tell whether or not a particular call will or won't do this, so this warning tends to be raised in many, many cases where (from my perspective as a user) nothing is actually amiss.
一个SettingWithCopy
警告引发对某些操作pandas
可能并没有达到预期的结果,因为他们可能会作用于副本而不是原始数据集。不幸的是,pandas 本身并没有简单的方法来判断一个特定的调用是否会这样做,所以这个警告往往会在很多很多情况下被提出,从我作为用户的角度来看,实际上没有任何问题.
Both of your method calls are fine. If you want to get rid of the warning entirely, you can specify:
你的两个方法调用都很好。如果你想完全摆脱警告,你可以指定:
pd.options.mode.chained_assignment = None
See this StackOverflow Q&Afor more information on this.
有关这方面的更多信息,请参阅此 StackOverflow 问答。