How to create a Pyspark Dataframe of combinations from list column

Viewed 1723

I currently have a pyspark dataframe like so:

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

My goal is to transform this dataframe (or create a new one) so that the new data is two length combinations of the items in the table.

I know that itertools.combinations can create combinations of lists, but I'm looking for a way to efficiently do this operation on a lot of data and I could not figure out how to integrate it with PySpark.

Example Result:

+-------------+-------------+
|        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 Answers

You can use itertools.combinations with 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   |
#+-----+-----+
Related