哪一个字符串与一个主字符串列表的pyframe相交?

2024-06-17 00:50:42 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这样一个数据帧。在

[Row(case_number='5307793179', word_list=['n', 'b', 'c']),
 Row(case_number='5307793171', word_list=['w', 'e', 'c']),
 Row(case_number='5307793172', word_list=['1', 'f', 'c']),
 Row(case_number='5307793173', word_list=['a', 'k', 'c']),
 Row(case_number='5307793174', word_list=['z', 'l', 'c']),
 Row(case_number='5307793175', word_list=['b', 'r', 'c'])]

还有一个像这样的主单词表:

^{pr2}$

有没有一种平滑的方法可以根据主单词表过滤word_列表,从而生成的pyspark数据帧如下所示。(我所说的sleek是指不使用udf,如果udf是最好/唯一的方法,我也会接受它作为解决方案)

[Row(case_number='5307793179', word_list=['b', 'c']),
 Row(case_number='5307793171', word_list=['c']),
 Row(case_number='5307793172', word_list=['c']),
 Row(case_number='5307793173', word_list=['c']),
 Row(case_number='5307793174', word_list=['c']),
 Row(case_number='5307793175', word_list=['b', 'c'])]

Tags: 数据方法number列表解决方案listpysparkword
1条回答
网友
1楼 · 发布于 2024-06-17 00:50:42

^{}从Spark 2.4开始提供:

pyspark.sql.functions.array_intersect(col1, col2)

Collection function: returns an array of the elements in the intersection of col1 and col2, without duplicates.

Parameters:

  • col1 – name of column containing array
  • col2 – name of column containing array
from pyspark.sql.functions import array, array_intersect, lit

master_word_list_col = array(*[lit(x) for x in master_word_list])

df = spark.createDataFrame(
    [("5307793179", ["n", "b", "c"])], 
    ("case_number", "word_list")
)

df.withColumn("word_list", array_intersect("word_list", master_word_list_col)).show()
^{pr2}$

相关问题 更多 >