kokochopper
kokochopper

Reputation: 39

How to fill the Nan value based on the other table in Python?

I have a table with lots of Nan values in 'Rating':

Category Rating
A 3.4
C Nan
B 4.0
A Nan
A 3.5
B Nan
C 4.0
A Nan
... ...

Then I calculate the mean value of each category in Python and create another table:

Category Mean_rating
A 4.3
B 3.9
C 3.2

How to fill this mean value into the first table based on the 'Category'?

Upvotes: 4

Views: 111

Answers (1)

BENY
BENY

Reputation: 323326

We can do transform create the mean and fillna

df.Rating.fillna(df.groupby('Category').Rating.transform('mean'),inplace=True)
df
  Category  Rating
0        A    3.40
1        C    4.00
2        B    4.00
3        A    3.45
4        A    3.50
5        B    4.00
6        C    4.00
7        A    3.45

Upvotes: 1

Related Questions