[英]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.