How to impute missing values with groupby if the group has less than 3 nan

Dataframe has 3 columns of “type”, “State”, “price”, with missing values in price column.

Sample Dataframe:

type   state   price

CHR     NSW     1.2
CHR     VIC     nan
Kia     NSW     2

I want to impute missing values if there are less than 3 nan in “price” column after groupby based on both “type” and “State”, otherwise nan.

Some codes looks like the below:

> df_daily_grouped = df_daily.groupby(['type', 'State'])
> df_daily_grouped["price"] = df_daily_grouped("price").transform(lambdax: x.fillna(x.mean()) if x.count() < 3, axis=1 )

Thanks

Answer

Try slightly modify your solution

df_daily_grouped['price'].transform(lambda x : x.fillna(x.mean()) if x.isnull().sum()<3 else x)