# How to fill in missing value of the mean of the other columns?

I had a movie dataset including 'budget' and 'genres' attributes.

I'd like to fill in the missing value of budget with the mean budget of each genre.

I first create two dataframes with or without budget.

BudgetNull = data[data['budget'].isnull()]
BudgetNotNull = data[data['budget'].notnull()]


Then, calculate the mean budget of each genre based on the BudgetNotNull dataset.

budget_of_genre = BudgetNotNull.groupby('genres')['budget'].mean()


Finally, I'd like to fill in the budget of BudgetNull based on its genre.

For instance, 'Marine Boy' is a action movie, therefore, fill in budget_of_genre['Action'].

How do I do this via for loop? Or there's other ways?

Using a transform as follows could work:

df["budget"] = df.groupby("genres")["budget"].transform(lambda x: x.fillna(x.mean()))


The mean calculation uses only the non-null values in its calculation. So the mean of each group's non-null values are imputed to that same group's null values.