Pandas: filling missing values by mean in each group

前端 未结 9 998
耶瑟儿~
耶瑟儿~ 2020-11-22 06:06

This should be straightforward, but the closest thing I\'ve found is this post: pandas: Filling missing values within a group, and I still can\'t solve my problem....

<
9条回答
  •  旧时难觅i
    2020-11-22 06:39

    fillna + groupby + transform + mean

    This seems intuitive:

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

    The groupby + transform syntax maps the groupwise mean to the index of the original dataframe. This is roughly equivalent to @DSM's solution, but avoids the need to define an anonymous lambda function.

提交回复
热议问题