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

后端 未结 3 2031
别那么骄傲
别那么骄傲 2021-02-05 01:15

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\\ipykerne         


        
3条回答
  •  攒了一身酷
    2021-02-05 01:59

    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.

提交回复
热议问题