我使用的是 Spark 2.4。
我在 Spark 数据框中有一个 ArrayType(StringType()) 列和一个 StringType() 列。我需要找到 StringType() 列在 ArrayType(StringType()) 列中的位置。
示例输入:
+---------------+---------+
|arrayCol |stringCol|
+---------------+---------+
|['a', 'b', 'c']|'b' |
+---------------+---------+
|['a', 'b', 'c']|'d' |
+---------------+---------+
示例输出:
+---------------+---------+-----+
|arrayCol |stringCol|Index|
+---------------+---------+-----+
|['a', 'b', 'c']|'b' |2 |
+---------------+---------+-----+
|['a', 'b', 'c']|'d' |null |
+---------------+---------+-----+
我尝试过 array_position 但它不起作用,并且收到“列不可迭代”错误。
我也尝试过组合 expr、transform 和 array_position,但我想知道是否有不需要使用 expr 的解决方案。
谢谢:)
最佳答案
尝试使用 expr
和 array_position
函数。
示例:
df.show()
#+---------+---------+
#| arrayCol|stringCol|
#+---------+---------+
#|[a, b, c]| b|
#|[a, b, c]| d|
#+---------+---------+
from pyspark.sql.functions import *
df.withColumn("Index",expr('if(array_position(arrayCol,stringCol)=0,null,array_position(arrayCol,stringCol))')).\
show()
#+---------+---------+-----+
#| arrayCol|stringCol|Index|
#+---------+---------+-----+
#|[a, b, c]| b| 2|
#|[a, b, c]| d| null|
#+---------+---------+-----+
关于apache-spark - 如何在pyspark中获取ArrayType()另一列中某一列的值的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63747044/