0

I would like to replace values in a particular column of a data frame. I tried several methods but they either do not work or they elicit a SettingWithCopyWarning. I would like to understand what the proper way would be. I found some older questions but I think they are based on an outdated syntax and do not reflect the current 'good practice'.

At first I tried

df.loc[:,['UNDERINFL']].replace(['N','Y'],['0', '1'], inplace = True)

This does not elicit any error or warning but it also does not replace anything.

Then I tried

df.loc[:,['UNDERINFL']] = df.loc[:,['UNDERINFL']].replace(['N','Y'],['0', '1'])

This works but it also throws the SettingWithCopyWarning and encourages me to use .loc = value, which I thought I am doing.

Can someone tell me the proper way to do this?

Secco
  • 15
  • 1
  • 3
  • 1
    `df['UNDERINFL'] = df['UNDERINFL'].replace(['N','Y'],['0', '1'])` – Quang Hoang Oct 07 '20 at 19:47
  • This works as well but it also throws the same warning. Could it just be a Jupyter Notebook issue? – Secco Oct 07 '20 at 19:51
  • That's because your `df` seems to be a part of an event bigger dataframe. How did you define your `df`? – Quang Hoang Oct 07 '20 at 19:52
  • Good call! Before I wanted to replace the values, I attempted to remove all the rows where this particular column had no values with `df = df[df.loc[:,'UNDERINFL'].notnull()]`. I guess this must have replaced `df` with a view of itself. Using `df = df[df.loc[:,'UNDERINFL'].notnull()].copy()` makes the following 'replace' line run without any warning. – Secco Oct 07 '20 at 20:44

0 Answers0