将数组传递给 Spark Lit 函数

Passing Array to Spark Lit function

假设我有一个包含数字 1-10 的 numpy 数组 a:
[1 2 3 4 5 6 7 8 9 10]

我还有一个 Spark 数据框,我想将我的 numpy 数组添加到其中 a。我认为一列文字可以完成这项工作。这不起作用:

df = df.withColumn("NewColumn", F.lit(a))

Unsupported literal type class java.util.ArrayList

但这行得通:

df = df.withColumn("NewColumn", F.lit(a[0]))

怎么做?

示例 DF 之前:

col1
a b c d e f g h i j

预期结果:

col1 NewColumn
a b c d e f g h i j 1 2 3 4 5 6 7 8 9 10

Spark 中的列表理解 array

a = [1,2,3,4,5,6,7,8,9,10]
df = spark.createDataFrame([['a b c d e f g h i j '],], ['col1'])
df = df.withColumn("NewColumn", F.array([F.lit(x) for x in a]))

df.show(truncate=False)
df.printSchema()
#  +--------------------+-------------------------------+
#  |col1                |NewColumn                      |
#  +--------------------+-------------------------------+
#  |a b c d e f g h i j |[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]|
#  +--------------------+-------------------------------+
#  root
#   |-- col1: string (nullable = true)
#   |-- NewColumn: array (nullable = false)
#   |    |-- element: integer (containsNull = false)

@pault 评论 (Python 2.7):

You can hide the loop using map:
df.withColumn("NewColumn", F.array(map(F.lit, a)))

@abegehr 添加了Python3版本:

df.withColumn("NewColumn", F.array(*map(F.lit, a)))

Spark 的 udf

# Defining UDF
def arrayUdf():
    return a
callArrayUdf = F.udf(arrayUdf, T.ArrayType(T.IntegerType()))

# Calling UDF
df = df.withColumn("NewColumn", callArrayUdf())

输出相同。

在 scala API 中,我们可以使用 "typedLit" 函数在列中添加数组或映射值。

// 参考:https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$

下面是添加数组或映射作为列值的示例代码。

import org.apache.spark.sql.functions.typedLit

val df1 = Seq((1, 0), (2, 3)).toDF("a", "b")

df1.withColumn("seq", typedLit(Seq(1,2,3)))
    .withColumn("map", typedLit(Map(1 -> 2)))
    .show(truncate=false)

// 输出

+---+---+---------+--------+
|a  |b  |seq      |map     |
+---+---+---------+--------+
|1  |0  |[1, 2, 3]|[1 -> 2]|
|2  |3  |[1, 2, 3]|[1 -> 2]|
+---+---+---------+--------+

希望对您有所帮助。