[英]PySpark - compare single list of integers to column of lists
我正在嘗試檢查 spark 數據框中的哪些條目(帶列表的列)包含給定列表中的最大數量的值。
我想出的最好方法是使用rdd.foreach()
迭代數據幀,並使用 python 的set1.intersection(set2)
將給定列表與每個條目進行比較。
我的問題是 spark 是否有任何內置功能,因此可以避免使用.foreach
進行迭代?
感謝您的幫助!
PS我的數據框看起來像這樣:
+-------------+---------------------+
| cardnumber|collect_list(article)|
+-------------+---------------------+
|2310000000855| [12480, 49627, 80...|
|2310000008455| [35531, 22564, 15...|
|2310000011462| [117112, 156087, ...|
+-------------+---------------------+
我正在嘗試使用給定的文章列表在第二列中找到交叉點最多的條目,例如[151574, 87239, 117908, 162475, 48599]
您可以在數據框中嘗試相同的設置操作,而不是使用 rdd.foreach:
from pyspark.sql.functions import udf, li, col
my_udf=udf(lambda A,B: list(set(A).intersection(set(B))))
df=df.withColumn('intersect_value', my_udf('A', 'B'))
您可以使用 len 函數獲取 UDF 本身中相交列表的大小,並從此數據幀執行您想要的操作。
這里唯一的選擇是udf
,但不會有太大區別。
from pyspark.sql.functions import udf, li, col
def intersect(xs):
xs = set(xs)
@udf("array<long>")
def _(ys):
return list(xs.intersection(ys))
return _
它可以應用為:
a_list = [1, 4, 6]
df = spark.createDataFrame([
(1, [3, 4, 8]), (2, [7, 2, 6])
], ("id", "articles"))
df.withColumn("intersect", intersect(a_list)("articles")).show()
# +---+---------+---------+
# | id| articles|intersect|
# +---+---------+---------+
# | 1|[3, 4, 8]| [4]|
# | 2|[7, 2, 6]| [6]|
# +---+---------+---------+
根據名稱,您似乎使用了collect_list
因此您的數據可能如下所示:
df_long = spark.createDataFrame([
(1, 3),(1, 4), (1, 8), (2, 7), (2, 7), (2, 6)
], ("id", "articles"))
在這種情況下,問題更簡單。 加入
lookup = spark.createDataFrame(a_list, "long").toDF("articles")
joined = lookup.join(df_long, ["articles"])
並匯總結果:
joined.groupBy("id").count().show()
# +---+-----+
# | id|count|
# +---+-----+
# | 1| 1|
# | 2| 1|
# +---+-----+
joined.groupBy("id").agg(collect_list("articles")).show()
# +---+----------------------+
# | id|collect_list(articles)|
# +---+----------------------+
# | 1| [4]|
# | 2| [6]|
# +---+----------------------+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.