15

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?

Stophface
  • 8,519
  • 25
  • 87
  • 179
Dance Party
  • 2,966
  • 10
  • 35
  • 62

3 Answers3

18

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

df2 = df.rename(columns={'one':'one_a'})
maxymoo
  • 32,647
  • 9
  • 86
  • 115
  • What if I did this? df = df.rename(columns={'one':'one_a'}) – Dance Party Nov 16 '15 at 04:41
  • And if I keep it as I had it, is it okay to ignore the warning in these cases? – Dance Party Nov 16 '15 at 04:43
  • It is OK to ignore it, but I would recommend you assign a list of new column names to `df.columns`. Basically, `df.columns = ['list', 'of', 'new', 'names']`. And for `df.drop`, it would be better to write `df = df.loc[:,['columns', 'to', 'keep']].copy()` – Kartik Nov 16 '15 at 04:48
  • @VinceBowdren well it's a matter of taste i suppose but inplace operations don't gel well with https://en.wikipedia.org/wiki/Functional_programming – maxymoo Apr 02 '17 at 22:51
  • How is it good programming practice to hold multiple copies of a dataset for renaming purposes only ? Would the size of the dataset affect your answer ? – Matias Andina Apr 02 '22 at 12:25
7

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

Community
  • 1
  • 1
renno
  • 2,499
  • 1
  • 23
  • 48
  • 2
    This might be my new strategy going forward to avoid these warnings -- copious amounts of `.copy()` tagged on to the ends of my operations – Monica Heddneck Nov 21 '18 at 03:41
1

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

df = df.drop(['one', 'two', 'three'], axis=1)
mehrdadorm
  • 19
  • 2