栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python-如何在Spark DataFrame中添加常量列?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python-如何在Spark DataFrame中添加常量列?

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
函数。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/407626.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号