我有如下表格:
ID start date name type
1 2020/01/01 cheese,meat A, B
1 2020/01/01 cheese,fruit A, C
所需的输出应该是:
ID start date count type
1 2020/01/01 cheese,meat,fruit A,B,C
我尝试使用 collect_list
和 collect_set
,但两者都不起作用。
最佳答案
您可以拆分和分解列,然后分组并收集集合:
import pyspark.sql.functions as F
df2 = df.withColumn(
'name',
F.explode(F.split('name', ','))
).withColumn(
'type',
F.explode(F.split('type', ','))
).groupBy(
'ID', 'start date'
).agg(
F.concat_ws(',', F.collect_set('name')).alias('name'),
F.concat_ws(',', F.collect_set('type')).alias('type')
)
df2.show()
+---+----------+-----------------+-----+
| ID|start date| name| type|
+---+----------+-----------------+-----+
| 1|2020/01/01|fruit,meat,cheese|C,B,A|
+---+----------+-----------------+-----+
关于python - Groupby 并将不同的值聚合为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66362678/