Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

python - Correct way to set new column in pandas DataFrame to avoid SettingWithCopyWarning

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

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

C:Anacondalibsite-packagesipykernel\__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

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'
question from:https://stackoverflow.com/questions/42379818/correct-way-to-set-new-column-in-pandas-dataframe-to-avoid-settingwithcopywarnin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Notes

By the Pandas Indexing Docs your code should work.

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

gets translated to

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

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,

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...