# 9.20:  Fill missing values within groups using the group mean.  Use .groupby() combined with
# .transform() to fill missing data contextually.

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'A': [1, 2, np.nan, 4],
    'B': [5, np.nan, np.nan, 8],
    'C': ['x', 'y', 'z', None]
})

df_grouped = df.copy()
df_grouped['Group'] = ['G1', 'G1', 'G2', 'G2']
df_grouped['A'] = df_grouped.groupby('Group')['A'].transform(lambda x: x.fillna(x.mean()))
df_grouped

