在 Pandas DataFrame 中设置新列以避免 SettingWithCopyWarning 的正确方法 [英] Correct way to set new column in pandas DataFrame to avoid SettingWithCopyWarning

查看:282
本文介绍了在 Pandas DataFrame 中设置新列以避免 SettingWithCopyWarning 的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图在 netc df 中创建一个新列,但我收到警告

Trying to create a new column in the netc df but i get the warning

netc["DeltaAMPP"] = netc.LOAD_AM - netc.VPP12_AM

C:\Anaconda\lib\site-packages\ipykernel\__main__.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

在较新版本的 Pandas 中创建字段以避免收到警告的正确方法是什么?

whats the proper way to create a field in the newer version of Pandas to avoid getting the warning?

pd.__version__
Out[45]:
u'0.19.2+0.g825876c.dirty'

推荐答案

正如错误中所说,尝试使用 .loc[row_indexer,col_indexer] 创建新列.

As it says in the error, try using .loc[row_indexer,col_indexer] to create the new column.

netc.loc[:,"DeltaAMPP"] = netc.LOAD_AM - netc.VPP12_AM.

注意事项

通过 Pandas 索引文档 你的代码应该可以工作.

Notes

By the Pandas Indexing Docs your code should work.

netc["DeltaAMPP"] = netc.LOAD_AM - netc.VPP12_AM

被翻译成

netc.__setitem__('DeltaAMPP', netc.LOAD_AM - netc.VPP12_AM)

哪些应该具有可预测的行为.SettingWithCopyWarning 仅用于警告用户在链式赋值期间出现意外行为(这不是您正在做的).但是,如文档中所述,

Which should have predictable behaviour. The SettingWithCopyWarning is only there to warn users of unexpected behaviour during chained assignment (which is not what you're doing). However, as mentioned in the docs,

有时在没有明显的链式索引时会出现 SettingWithCopy 警告.这些是 SettingWithCopy 旨在捕获的错误!Pandas 可能是想警告你你已经这样做了:

Sometimes a SettingWithCopy warning will arise at times when there’s no obvious chained indexing going on. These are the bugs that SettingWithCopy is designed to catch! Pandas is probably trying to warn you that you’ve done this:

然后文档继续给出一个示例,说明即使在意料之外的情况下也可能会出现该错误.因此,如果没有更多背景,我无法说出为什么会发生这种情况.

The docs then go on to give an example of when one might get that error even when it's not expected. So I can't tell why that's happening without more context.

这篇关于在 Pandas DataFrame 中设置新列以避免 SettingWithCopyWarning 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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