繁体   English   中英

如何在 Spark DataFrame 中逐行过滤?

[英]How to filter row by row in Spark DataFrame?

我有这样的火花 DataFrame :

 code             list_code
 1002             [1005, 1006, 1007, ....]
 1005             [1005, 1009, 1101, ....]

如何使用 pyspark 过滤 list_code 中的代码。 不知何故,它是逐行值。 普通代码不会像这样工作:

df.filter((df.code.isin(df.list_code)))

按照评论中的建议使用array_contains

import pyspark.sql.functions as F

df2 = df.filter(F.array_contains(F.col('list_code'), F.col('code')))

当列表是输入而不是列时,isin() 在 pyspark 中有效。 检查这个

df=spark.sql(""" with t1 (
 select 1002 code, array(1005, 1006, 1007) list_code union all 
 select 1005 code, array(1005, 1009, 1101) list_code
 ) select code, list_code from t1
 """)
df.show()


+----+------------------+
|code|         list_code|
+----+------------------+
|1002|[1005, 1006, 1007]|
|1005|[1005, 1009, 1101]|
+----+------------------+

in_arr=[2002,3002,1002]

df.filter((df.code.isin(in_arr))).show()

+----+------------------+
|code|         list_code|
+----+------------------+
|1002|[1005, 1006, 1007]|
+----+------------------+

如果要使用将一列与另一列进行比较,请使用 array_contains() function

df.createOrReplaceTempView("df")
spark.sql("  select code, list_code from df where array_contains(list_code, code) ").show()

+----+------------------+
|code|         list_code|
+----+------------------+
|1005|[1005, 1009, 1101]|
+----+------------------+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM