Replace null values of a pandas data frame with groupby mean value

1k views Asked by At

I have a data frame with below data:

df

I want to replace the null values of each country by its respective mean values.

For Eg, I have calculated the mean values with following code:

df2=df.groupby('country').mean()

mean

I have to replace the null values in df with corresponding mean value present in df2. If the mean value is NaN, then keep Nan, else the value.

I have tried with below code but failed : 1.Output still has NaN values:

Output still has NaN values

2.

df['retail'] = df['retail'].replace('',df.groupby('country').mean())

enter image description here

1

There are 1 answers

3
gtomer On

To replace nulls with the mean of the column you should do:

 df['transit_stations'] = df['transit_stations'].fillna(df2.groupby('country')['transit_stations'].transform('mean'))