Home > Software engineering >  Pandas fillna() in DataFrame not working with inplace = True
Pandas fillna() in DataFrame not working with inplace = True

Time:05-02

I'm working with the Titanic dataset from Kaggle and I'm trying to replace the NA values with 30, when the Pclass is 2. I've tried the following code, but value 30 doesn't seem to be saved in the dataframe.

data[data['Pclass']==2].fillna({'Age':30}, inplace = True)

The expected result should bee that all NA values in Pclass = 2 will be replaced with 30. But when I checke again, I still see NA Values.

data[data['Pclass']==2]

Output

Why doesn't inplace = True allowing me to save the replaced values in the original dataframe?

CodePudding user response:

you are working on the copy, use inplace with loc, create new var and then use inplace, in general dont use inplace in future

df=data.loc[data['Pclass']==2]
df.fillna({'Age':30}, inplace = True)

CodePudding user response:

As @sygneto mentioned, you are filling na to a subset of your data - it won't touch the original data.You know, when you get the warning SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.

I would personally locate the columns I want updated and would do it on a column basis. Something like:

data.loc[(data['Pclass']==2) & (data['Age'].isnull()),'Age']=30
  • Related