Chintan Panchal
Chintan Panchal

Reputation: 41

changing NaN values in the DataFrame

In a dataframe, i do have column "Gender" and "Score"

Gender:'M','F','F','M','F'
Score : np.NaN,200,400,300,np.NaN

I need to change 'NaN' values of 'Score' column with mean of that particular gender.

Tried following code, but not working:

df6['Score']=df6['Score'].
fillna(df6.groupby('Gender')['Score'].transform('mean'))

df6

Upvotes: 2

Views: 77

Answers (1)

piRSquared
piRSquared

Reputation: 294228

You can leave the result from transform as a dataframe and the fillna will work as intended.

df.fillna(df.groupby('Gender')[['Score']].transform('mean'))

  Gender  Score
0      M  300.0
1      F  200.0
2      F  400.0
3      M  300.0
4      F  300.0

Upvotes: 3

Related Questions