ARC*_*row 2 apache-spark pyspark
我正在使用火花2.4。
我在 Spark 数据框中有一个 ArrayType(StringType()) 列和一个 StringType() 列。我需要在 ArrayType(StringType()) 列中找到 StringType() 列的位置。
输入示例:
+---------------+---------+
|arrayCol |stringCol|
+---------------+---------+
|['a', 'b', 'c']|'b' |
+---------------+---------+
|['a', 'b', 'c']|'d' |
+---------------+---------+
Run Code Online (Sandbox Code Playgroud)
示例输出:
+---------------+---------+-----+
|arrayCol |stringCol|Index|
+---------------+---------+-----+
|['a', 'b', 'c']|'b' |2 |
+---------------+---------+-----+
|['a', 'b', 'c']|'d' |null |
+---------------+---------+-----+
Run Code Online (Sandbox Code Playgroud)
我尝试过 array_position 但它不起作用,并且出现“列不可迭代”错误。
我也尝试过组合 expr、transform 和 array_position,但我想知道是否有一个不需要使用 expr 的解决方案。
谢谢 :)
尝试使用exprwitharray_position函数。
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|
#+---------+---------+-----+
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1180 次 |
| 最近记录: |