比较两个数组并获得PySpark的差异

时间:2017-10-27 11:15:45

标签: python pyspark apache-spark-sql spark-dataframe apache-spark-mllib

我在数据框中有两个数组字段。

enter image description here

我需要比较这两个数组,并在同一数据框中作为数组(新列)获得差异。

预期输出为:

enter image description here

B列是A列的子集。此外,两个数组中的单词顺序相同。

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

您可以使用用户定义的功能。我的示例数据框与您的有点不同,但代码应该可以正常工作:

import pandas as pd
from pyspark.sql.types import *

#example df
df=sqlContext.createDataFrame(pd.DataFrame(data=[[["hello", "world"], 
["world"]],[["sample", "overflow", "text"], ["sample", "text"]]], columns=["A", "B"]))

# define udf
differencer=udf(lambda x,y: list(set(x)-set(y)), ArrayType(StringType()))
df=df.withColumn('difference', differencer('A', 'B'))

编辑:

如果存在重复项,则此功能无效,因为设置仅保留唯一身份。所以你可以修改udf如下:

differencer=udf(lambda x,y: [elt for elt in x if elt not in y] ), ArrayType(StringType()))

答案 1 :(得分:0)

自Spark 2.4.0起,可以使用array_except轻松解决此问题。 以示例

from pyspark.sql import functions as F

#example df
df=sqlContext.createDataFrame(pd.DataFrame(data=[[["hello", "world"], 
["world"]],[["sample", "overflow", "text"], ["sample", "text"]]], columns=["A", "B"]))


df=df.withColumn('difference', F.array_except('A', 'B'))

对于数组的更多类似操作,我建议这篇博文 https://www.waitingforcode.com/apache-spark-sql/apache-spark-2.4.0-features-array-higher-order-functions/read