df.loc causes a SettingWithCopyWarning warning message

后端 未结 1 844
小鲜肉
小鲜肉 2021-01-04 11:40

The following line of my code causes a warning :

import pandas as pd

s = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list(\'ABCD\'))
s.loc[         


        
相关标签:
1条回答
  • 2021-01-04 11:59

    The documentation is slightly confusing.

    Your dataframe is a copy of another dataframe. You can verify this by running bool(df.is_copy) You are getting the warning because you are trying to assign to this copy.

    The warning/documentation is telling you how you should have constructed df in the first place. Not how you should assign to it now that it is a copy.

    df = some_other_df[cols]
    

    will make df a copy of some_other_df. The warning suggests doing this instead

    df = some_other_df.loc[:, [cols]]
    

    Now that it is done, if you choose to ignore this warning, you could

    df = df.copy()
    

    or

    df.is_copy = None
    
    0 讨论(0)
提交回复
热议问题