【问题标题】:How to Convert Column into a List based on the other column in pyspark如何根据pyspark中的其他列将列转换为列表
【发布时间】:2023-02-07 12:47:53
【问题描述】:

我在 pyspark 中有一个数据框,如下所示:

| Column A | Column B |
| -------- | -------- |
| 123      | abc   |
| 123      | def   |
| 456      | klm   |
| 789      | nop   |
| 789      | qrst  | 

对于 A 列中的每一行,B 列必须转换为列表。结果应该是这样的。

| Column A | Column B |
| -------- | -------- |
| 123      |[abc,def] |
| 456      | [klm]    |
| 789      |[nop,qrst]|

我试过使用 map(),但它没有给我预期的结果。你能指出我如何解决这个问题的正确方向吗?

【问题讨论】:

  • 您是否尝试过使用 pyspark.sql.functions 中的 collect_list。你可以这样写:df.group_by(col("Column A")).agg(collect_list('Column B'))。请参阅@Steven 提到的评论中的文档。

标签: python dataframe pyspark


【解决方案1】:

使用collect_list

from pyspark.sql import functions as F
df1.groupBy("Column A").agg(F.collect_list("Column B")).show()

输入:

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多