繁体   English   中英

如何在pyspark中的ArrayType()的另一列中获取列的值的索引?

[英]How to get the index of value of a column in another column of ArrayType() in pyspark?

我正在使用火花 2.4。
我在 spark 数据框中有一个 ArrayType(StringType()) 列和一个 StringType() 列。 我需要在 ArrayType(StringType()) 列中找到 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 的解决方案
谢谢 :)

尝试使用带有array_position函数的expr

Example:

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|
#+---------+---------+-----+

暂无
暂无

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

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