I have a df1
Spark dataframe
id transactions
1 [1, 2, 3, 5]
2 [1, 2, 3, 6]
3 [1, 2, 9, 8]
4 [1, 2, 5, 6]
root
|-- id: int (nullable = true)
|-- transactions: array (nullable = false)
|-- element: int(containsNull = true)
None
I have a df2
Spark dataframe
items cost
[1] 1.0
[2] 1.0
[2, 1] 2.0
[6, 1] 2.0
root
|-- items: array (nullable = false)
|-- element: int (containsNull = true)
|-- cost: int (nullable = true)
None
我想检查items列中的所有数组元素是否都在transactions列中。
第一行([1, 2, 3, 5]
)包含来自items列的[1],[2],[2, 1]
。因此,我需要对它们对应的成本进行求和:1.0 + 1.0 + 2.0 = 4.0
我想要的输出结果是
"最初的回答"
id transactions score
1 [1, 2, 3, 5] 4.0
2 [1, 2, 3, 6] 6.0
3 [1, 2, 9, 8] 4.0
4 [1, 2, 5, 6] 6.0
我尝试使用collect()
/toLocalIterator
循环,但效率似乎不高。我将有大量数据。
我认为创建一个像这样的UDF可以解决它。但是它会抛出错误。
修改后:
我尝试使用collect()
/toLocalIterator
循环来处理数据,但效率不高,因为数据量太大。我认为创建一个UDF可以解决这个问题,但是执行时出现了错误。
from pyspark.sql.functions import udf
def containsAll(x, y):
result = all(elem in x for elem in y)
if result:
print("Yes, transactions contains all items")
else :
print("No")
contains_udf = udf(containsAll)
dataFrame.withColumn("result", contains_udf(df2.items, df1.transactions)).show()
有其他解决办法吗?最初的回答。
groupby
和sum
函数(不要使用循环或collect
函数)。你的数据框架模式是什么?请在问题中编辑并添加df.printSchema()
。我假设这些列表是整数数组 - 如果是这样,请参考以下帖子了解如何连接这两个数据框架:PySpark Join on Values Within A List。 - paultdf1
和df2
的大小关系如何? - cph_sto