Pandas SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

前端 未结 2 407
攒了一身酷
攒了一身酷 2021-01-11 22:25

I keep getting the warning in the subject in the following situations:

  1. df.rename(columns={\'one\':\'one_a\'}, inplace=True)

  2. df.drop([\'one\'

相关标签:
2条回答
  • 2021-01-11 22:46

    Easiest fix (and probably good programming practice) would be to not do inplace operations, e.g.

    df2 = df.rename(columns={'one':'one_a'})
    
    0 讨论(0)
  • 2021-01-11 23:00

    I had a similar problem and to fix I did the following:

    new_df = df.copy()
    new_df.rename(columns={'one':'one_a'}, inplace=True)
    new_df.drop(['one', 'two', 'three'], axis=1, inplace=True)
    

    Or you can do

    df.is_copy = False
    

    You were probably using a copy of your original DF (ex: you were manipulating your DF before that) and that's why you were receiving the warning. More on copy:

    why should I make a copy of a data frame in pandas

    0 讨论(0)
提交回复
热议问题