26

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?

four-eyes
  • 10,740
  • 29
  • 111
  • 220
Dance Party
  • 3,459
  • 10
  • 42
  • 67

4 Answers4

26

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

df2 = df.rename(columns={'one':'one_a'})
maxymoo
  • 35,286
  • 11
  • 92
  • 119
  • 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
  • 15
    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
10

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,659
  • 2
  • 27
  • 58
  • 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
4

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

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

if you are work with jupyter notebook you can restart and runall . when i got this error then restart and run and it works fine with same code.

movies.dropna(inplace=True)