gpt4 book ai didi

python - Groupby 并将不同的值聚合为字符串

转载 作者:行者123 更新时间:2023-12-01 23:30:26 37 4
gpt4 key购买 nike

我有如下表格:

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_listcollect_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/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com