Pandas - 填充特定类别的平均值

Was*_*and 3 python pandas fillna

我想用列的平均数填充,但仅用于与缺失值相同类别的代表

data = {'Class': ['Superlight', 'Aero', 'Aero', 'Superlight', 'Superlight', 'Superlight', 'Aero', 'Aero'],
        'Weight': [5.6, 8.6, np.nan, 5.9, 5.65, np.nan, 8.1, 8.4]}


    Class   Weight
0   Superlight     5.60
1   Aero           8.60
2   Aero           NaN
3   Superlight     5.90
4   Superlight     5.65
5   Superlight     NaN
6   Aero           8.10
7   Aero           8.40
Run Code Online (Sandbox Code Playgroud)

我知道我可以做到:

df.Weight.fillna(df.Weight.mean())
Run Code Online (Sandbox Code Playgroud)

但这将用整列的平均值填充缺失值。

以下将用 AERO 类别的平均值替换空值(这更好,但仍然不好,因为我必须分别为每个类别/类别做这件事)

df.Weight.fillna(df[df.Class == 'Aero'].Weight.mean())
Run Code Online (Sandbox Code Playgroud)

是否可以对其进行抽象,以便它自动获取当前行的 Class 并找到属于该类别的值的平均值并替换它而不对 Class 值进行硬编码?希望这是有道理的。

ank*_*_91 6

groupby + transform 然后填写:

df['Weight'].fillna(df.groupby("Class")['Weight'].transform("mean"))
Run Code Online (Sandbox Code Playgroud)
0    5.600000
1    8.600000
2    8.366667
3    5.900000
4    5.650000
5    5.716667
6    8.100000
7    8.400000
Name: Weight, dtype: float64
Run Code Online (Sandbox Code Playgroud)