[英]How to create a Pyspark Dataframe of combinations from list column
我目前有一個 pyspark dataframe 像這樣:
+--------------------+
| items|
+--------------------+
| [1, 2, 3, 4]|
| [1, 5, 7]|
| [9, 10]|
| ...|
我的目標是轉換這個 dataframe(或創建一個新數據),以便新數據是表中項目的兩個長度組合。
我知道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|
| ...|
您可以將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 |
#+-----+-----+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.