比较两个数组并获得 PySpark 中的差异
Comparing two arrays and getting the difference in PySpark
我在一个数据框中有两个数组字段。
我需要比较这两个数组,并在同一数据框中以数组(新列)的形式获取差异。
预期输出为:
B 列是 A 列的子集。此外,单词在两个数组中的顺序相同。
谁能帮我解决这个问题?
您可以使用用户定义的函数。我的示例数据框与您的略有不同,但代码应该可以正常工作:
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()))
从 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
我在一个数据框中有两个数组字段。
我需要比较这两个数组,并在同一数据框中以数组(新列)的形式获取差异。
预期输出为:
B 列是 A 列的子集。此外,单词在两个数组中的顺序相同。
谁能帮我解决这个问题?
您可以使用用户定义的函数。我的示例数据框与您的略有不同,但代码应该可以正常工作:
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()))
从 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