首页 > 解决方案 > 如何在pyspark中做多个array_union和array_intersection

问题描述

假设我有一个 pyspark 数据框,其中包含以下列:数组类型的 c1、c2、c3、c4 和 c5。现在如果我想做:(c1)交集(c2 union c3)交集(c2 union c4 union c5)

我可以在循环中的两列上使用 array_union 并在 withColumn 的帮助下继续添加一列,然后类似地进行一轮交叉。

如何在 PySpark 中有效地做到这一点?有没有更聪明的方法来做到这一点?

标签: apache-sparkpysparkpyspark-sqlpyspark-dataframes

解决方案


你不需要使用循环,你可以有一个大withColumn语句。这也应该是最快的选择,因为您只使用 spark 内置函数。

from pyspark.sql import functions as f
df = df.withColumn("crazy_set_operation",
                    f.array_intersect(f.col("c1"),
                                      f.array_intersect(
                                          f.array_union(f.col("c2"), f.col("c3")),
                                          f.array_union(f.array_union(f.col("c2"), F.col("c4")), f.col("c5"))
                                          )
                                      )
                   )


推荐阅读