从pyspark中的dataframe ArrayType列获取前N个元素

Vip*_*rma 5 apache-spark apache-spark-sql pyspark

我有一个火花数据帧,行为 -

1   |   [a, b, c]
2   |   [d, e, f]
3   |   [g, h, i]
Run Code Online (Sandbox Code Playgroud)

现在我想只保留数组列中的前2个元素.

1   |   [a, b]
2   |   [d, e]
3   |   [g, h]
Run Code Online (Sandbox Code Playgroud)

怎么能实现呢?

注意 - 请记住,我不是在这里提取单个数组元素,而是可能包含多个元素的数组的一部分.

pau*_*ult 7

以下是使用API​​函数的方法.

假设您的DataFrame如下:

df.show()
#+---+---------+
#| id|  letters|
#+---+---------+
#|  1|[a, b, c]|
#|  2|[d, e, f]|
#|  3|[g, h, i]|
#+---+---------+

df.printSchema()
#root
# |-- id: long (nullable = true)
# |-- letters: array (nullable = true)
# |    |-- element: string (containsNull = true)
Run Code Online (Sandbox Code Playgroud)

您可以使用方括号letters按索引访问列中的元素,并将其包装在调用中pyspark.sql.functions.array()以创建新ArrayType列.

import pyspark.sql.functions as f

df.withColumn("first_two", f.array([f.col("letters")[0], f.col("letters")[1]])).show()
#+---+---------+---------+
#| id|  letters|first_two|
#+---+---------+---------+
#|  1|[a, b, c]|   [a, b]|
#|  2|[d, e, f]|   [d, e]|
#|  3|[g, h, i]|   [g, h]|
#+---+---------+---------+
Run Code Online (Sandbox Code Playgroud)

或者,如果要列出的索引太多,则可以使用列表推导:

df.withColumn("first_two", f.array([f.col("letters")[i] for i in range(2)])).show()
#+---+---------+---------+
#| id|  letters|first_two|
#+---+---------+---------+
#|  1|[a, b, c]|   [a, b]|
#|  2|[d, e, f]|   [d, e]|
#|  3|[g, h, i]|   [g, h]|
#+---+---------+---------+
Run Code Online (Sandbox Code Playgroud)