Pandas: How to fill null values with mean of a groupby?

后端 未结 2 1288
长发绾君心
长发绾君心 2020-12-10 14:47

I have a dataset will some missing data that looks like this:

id    category     value
1     A            NaN
2     B            NaN
3     A            10.5
         


        
2条回答
  •  孤街浪徒
    2020-12-10 15:29

    You can also use GroupBy + transform to fill NaN values with groupwise means. This method avoids inefficient apply + lambda. For example:

    df['value'] = df['value'].fillna(df.groupby('category')['value'].transform('mean'))
    df['value'] = df['value'].fillna(df['value'].mean())
    

提交回复
热议问题