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

后端 未结 3 2028
别那么骄傲
别那么骄傲 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:49

    Your example is incomplete, as it doesn't show where netc comes from. It is likely that netc itself is the product of slicing, and as such Pandas cannot make guarantees that it isn't a view or a copy.

    For example, if you're doing this:

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

    then Pandas wouldn't know if netc is a view or a copy. If it were a one-liner, it would effectively be like this:

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

    where you can see the double indexing more clearly.

    If you want to make netc separate from netb, one possible remedy might be to force a copy in the first line (the loc is to make sure we're not copying two times), like:

    netc = netb.loc[netb["DeltaAMPP"] == 0].copy()
    

    If, on the other hand, you want to have netb modified with the new column, you may do:

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

提交回复
热议问题