使用相对于 Python 中另一列的列模式填充缺失值

Filling missing values with mode of column relative to another column in Python

我有一个包含 2 列 City_Type 和 Vehicle_Type 以及许多其他列的数据框。现在我在 Vehicle_Type 列中有一些缺失值,我需要根据 City_Type 使用 Vehicle_Type 模式进行估算。 首先,我需要编写一个 python 程序来获得以下输出。然后我需要根据以下输出在 Vehicle_Type 字段中填充缺失值。

City_Type    Vehicle_Type
Tier1        Sedans
Tier2        Hatchback
Tier3        SUV

您可以将 groupby 和 fillna 与模式一起使用

df.groupby('City_Type').Vehicle_Type.transform(lambda x: x.fillna(x.mode()[0]))