pivot-table - 如何在pyspark中没有聚合功能的数据透视表
问题描述
我在 pyspark 中有一个这样的数据框。
|--------------|----------------|---------------|
| col_1 | col_2 | col_3 |
|-----------------------------------------------|
| 1 | A | abd |
|-----------------------------------------------|
| 1 | B | acd |
|-----------------------------------------------|
| 1 | A | bcd |
|-----------------------------------------------|
| 1 | B | ceg |
------------------------------------------------|
| 2 | A | cgs |
|-----------------------------------------------|
| 2 | B | bsc |
|-----------------------------------------------|
| 2 | A | iow |
|-----------------------------------------------|
我想把表转成这个。
|--------------|----------------|---------------|
| col_1 | A | B |
|-----------------------------------------------|
| 1 | abd | acd |
|-----------------------------------------------|
| 1 | bcd | ceg |
|-----------------------------------------------|
| 2 | cgs | bsc |
|-----------------------------------------------|
| 2 | iow | null |
------------------------------------------------|
我该怎么做?pyspark 数据框的数据透视函数需要聚合函数,在我的情况下col_1
也不是唯一的。
解决方案
这是一种可以获得目标结果的方法:
import pyspark.sql.functions as F
df = df.groupBy('col_1').pivot("col_2").agg(F.collect_list("col_3"))
cols = df.columns[1:]
res = df.select("col_1",F.explode(cols[0]).alias(cols[0])).withColumn("id", F.monotonically_increasing_id())
for name in cols[1:]:
res = res.join(df.select("col_1",F.explode(name).alias(name)).withColumn("id", F.monotonically_increasing_id()),on = ["id","col_1"], how = "outer")
res = res.orderBy("col_1").drop("id")