Menu Close

How to fill missing values by mean in each group with Python Pandas?

Sometimes, we want to fill missing values by mean in each group with Python Pandas.

In this article, we’ll look at how to fill missing values by mean in each group with Python Pandas.

How to fill missing values by mean in each group with Python Pandas?

To fill missing values by mean in each group with Python Pandas, we can use the transform method.

For instance, we write

df["value"] = df.groupby("name").transform(lambda x: x.fillna(x.mean()))

to call groupby with 'name' to group by the name column.

And then we call transform with a lambda function that calls fillna with the mean of the values grouped by name.

Finally, we assign the returned values to the data frame df‘s value column.

Conclusion

To fill missing values by mean in each group with Python Pandas, we can use the transform method.

Posted in Python, Python Answers