Spark 2.2+
Spark 2.2引入
typedLit了
support Seq,
Map和
Tuples(SPARK-19254),并且应该支持以下调用(Scala):
import org.apache.spark.sql.functions.typedLitdf.withColumn("some_array", typedLit(Seq(1, 2, 3)))df.withColumn("some_struct", typedLit(("foo", 1, .0.3)))df.withColumn("some_map", typedLit(Map("key1" -> 1, "key2" -> 2)))星火1.3+(lit),1.4+(array,struct),2.0+(map):的第二个参数
Dataframe.withColumn应该是
a,
Column因此你必须使用文字:
from pyspark.sql.functions import litdf.withColumn('new_column', lit(10))如果你需要复杂的列,则可以使用以下代码块构建这些列
array:
from pyspark.sql.functions import array, create_map, structdf.withColumn("some_array", array(lit(1), lit(2), lit(3)))df.withColumn("some_struct", struct(lit("foo"), lit(1), lit(.3)))df.withColumn("some_map", create_map(lit("key1"), lit(1), lit("key2"), lit(2)))可以在
Scala中使用完全相同的方法。
import org.apache.spark.sql.functions.{array, lit, map, struct}df.withColumn("new_column", lit(10))df.withColumn("map", map(lit("key1"), lit(1), lit("key2"), lit(2)))为了提供名称
structs或者使用
alias上的每个字段:
df.withColumn( "some_struct", struct(lit("foo").alias("x"), lit(1).alias("y"), lit(0.3).alias("z")) )或
cast整个对象
df.withColumn( "some_struct", struct(lit("foo"), lit(1), lit(0.3)).cast("struct<x: string, y: integer, z: double>") )尽管较慢,也可以使用
UDF。
注意事项:
可以使用相同的构造将常量参数传递给
UDF或
SQL函数。



