如何从列表列创建组合的 Pyspark Dataframe [英] How to create a Pyspark Dataframe of combinations from list column

查看:33
本文介绍了如何从列表列创建组合的 Pyspark Dataframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

示例结果:

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

推荐答案

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

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

这篇关于如何从列表列创建组合的 Pyspark Dataframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆