将数组传递到火花点亮功能



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

我也有一个火花数据框,我想添加我的numpy数组a。我认为一列文字将完成这项工作。这行不通:

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

不支持的字面类型类Java.util.arraylist

但这有效:

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

如何做?

示例DF之前:

col1
a b c d e f g h i j

列表理解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(

您可以使用map隐藏循环:
df.withColumn("NewColumn", F.array(map(F.lit, a)))

@ abegehr添加 python 3 版本:

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.ssql.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]|
+---+---+---------+--------+

我希望这会有所帮助。

最新更新