且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Pandas DataFrame 中设置新列以避免 SettingWithCopyWarning 的正确方法

更新时间:2023-12-01 14:52:22

正如错误中所说,尝试使用 .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.