如何从列表列

时间:2021-02-08 21:09:53

标签: python apache-spark pyspark apache-spark-sql pyspark-dataframes

我目前有一个像这样的 pyspark 数据框:

+--------------------+
|               items|
+--------------------+
|        [1, 2, 3, 4]|
|           [1, 5, 7]|
|             [9, 10]|
|                 ...|

我的目标是转换此数据框(或创建一个新数据框),以便新数据是表中项目的两种长度组合。

我知道 itertools.combinations 可以创建列表组合,但我正在寻找一种方法来有效地对大量数据执行此操作,但我不知道如何将其与 PySpark 集成。

>

示例结果:

+-------------+-------------+
|        item1|        item2|
+-------------+-------------+
|            1|            2|
|            2|            1|
|            1|            3|
|            3|            1|
|            1|            4|
|            4|            1|
|            2|            3|
|            3|            2|
|            2|            4|
|            4|            2|
|            3|            4|
|            4|            3|
|            1|            5|
|            5|            1|
|            1|            7|
|            7|            1|
|            5|            7|
|            7|            5|
|            9|           10|
|           10|            9|
|                        ...|

1 个答案:

答案 0 :(得分:1)

您可以将 itertools.combinations 与 UDF 一起使用:

import itertools
from pyspark.sql import functions as F

combinations_udf = F.udf(
    lambda x: list(itertools.combinations(x, 2)),
    "array<struct<item1:int,item2:int>>"
)

df1 = df.withColumn("items", F.explode(combinations_udf(F.col("items")))) \
    .selectExpr("items.*")

df1.show()

#+-----+-----+
#|item1|item2|
#+-----+-----+
#|1    |2    |
#|1    |3    |
#|1    |4    |
#|2    |3    |
#|2    |4    |
#|3    |4    |
#|1    |5    |
#|1    |7    |
#|5    |7    |
#|9    |10   |
#+-----+-----+
相关问题