pandas 映射到新列SettingWithCopyWarning [英] Pandas map to a new column, SettingWithCopyWarning

查看:307
本文介绍了 pandas 映射到新列SettingWithCopyWarning的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在pandas数据框中,我试图映射df ['old_column'],为每行应用用户定义的函数 f 并创建一个新列.

In pandas data frame, I'm trying to map df['old_column'], apply user defined function f for each row and create a new column.

df['new_column'] = df['old_column'].map(lambda x: f(x))

这将给出"SettingWithCopyWarning:试图在来自DataFrame的切片的副本上设置一个值".错误.

This will give out "SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame." error.

我尝试了以下操作:

df.loc[:, 'new_column'] = df['old_column'].map(lambda x: f(x))

这无济于事.我该怎么办?

which doesn't help. What can I do?

推荐答案

对于pandas中的某些操作,可能会发出SettingWithCopy警告,该操作可能没有预期的结果,因为它们可能作用于副本而不是原始数据集.不幸的是,熊猫本身并没有简单的方法来判断特定呼叫是否会这样做,因此在许多情况下(从我的观点来看,用户)实际上什么都不对.

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 itself to 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.

两个方法调用都可以.如果要完全消除警告,可以指定:

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

有关此信息,请参阅此StackOverflow问题与解答.

See this StackOverflow Q&A for more information on this.

这篇关于 pandas 映射到新列SettingWithCopyWarning的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆