Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

pandas

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

Step 1:

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

Step 2:

df.drop(['one', 'two', 'three'], axis=1, inplace=True)

How do I fix?

like image 595
Dance Party Avatar asked Nov 16 '15 02:11

Dance Party


3 Answers

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

like image 164
renno Avatar answered Nov 09 '22 20:11

renno


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

df2 = df.rename(columns={'one':'one_a'})
like image 21
maxymoo Avatar answered Nov 09 '22 18:11

maxymoo


One way around it is to remove inplace=True, then use:

df = df.drop(['one', 'two', 'three'], axis=1)
like image 2
mehrdadorm Avatar answered Nov 09 '22 20:11

mehrdadorm