Reputation: 1082
I would like to fill NaN based on a column values' mean. Example:
Groups Temp
1 5 27
2 5 23
3 5 NaN (will be replaced by 25)
4 1 NaN (will be replaced by the mean of the Temps that are in group 1)
Any suggestions ? Thanks !
Upvotes: 1
Views: 81
Reputation: 153510
Use groupby
, transfrom
, and lamdba function with fillna
and mean
:
df = df.assign(Temp=df.groupby('Groups')['Temp'].transform(lambda x: x.fillna(x.mean())))
print(df)
Output:
Temp
0 27.0
1 23.0
2 25.0
3 NaN
Upvotes: 2