Pivot table 和 pyspark 中的 onehot

Pivot table and onehot in pyspark

我有一个 pyspark 数据框,它看起来像 -

id      age      cost     gender
1        38       230      M
2        40       832      M
3        53       987      F
1        38       764      M
4        63       872      F
5        21       763      F

我希望我的数据框看起来像 -

id      age      cost     gender    M       F
1        38       230      M        1       0
2        40       832      M        1       0
3        53       987      F        0       1
1        38       764      M        1       0
4        63       872      F        0       1
5        21       763      F        0       1
4        63      1872      F        0       1

使用python我可以按以下方式管理-

final_df = pd.concat([df.drop(['gender'], axis=1), pd.get_dummies(df['gender'])], axis=1)

如何在pyspark中管理?

只需要添加 2 列:

from pyspark.sql import functions as F
final_df = df.select(
    "id",
    "age",
    "cost",
    "gender",
    F.when(F.col("gender")==F.lit("M"),1).otherwise(0).alias("M"),
    F.when(F.col("gender")==F.lit("F"),1).otherwise(0).alias("F"),
)