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

标签 python apache-spark dataframe pyspark apache-spark-sql

我想在 DataFrame 中添加一列具有一些任意值(每行都相同)。使用 withColumn 时出现错误如下:

dt.withColumn('new_column', 10).head(5)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-50-a6d0257ca2be> in <module>()
      1 dt = (messages
      2     .select(messages.fromuserid, messages.messagetype, floor(messages.datetime/(1000*60*5)).alias("dt")))
----> 3 dt.withColumn('new_column', 10).head(5)

/Users/evanzamir/spark-1.4.1/python/pyspark/sql/dataframe.pyc in withColumn(self, colName, col)
   1166         [Row(age=2, name=u'Alice', age2=4), Row(age=5, name=u'Bob', age2=7)]
   1167         """
-> 1168         return self.select('*', col.alias(colName))
   1169 
   1170     @ignore_unicode_prefix

AttributeError: 'int' object has no attribute 'alias'

似乎我可以通过添加和减去其他列之一(因此它们添加为零)然后添加我想要的数字(在这种情况下为 10)来欺骗函数按照我想要的方式工作:
dt.withColumn('new_column', dt.messagetype - dt.messagetype + 10).head(5)

[Row(fromuserid=425, messagetype=1, dt=4809600.0, new_column=10),
 Row(fromuserid=47019141, messagetype=1, dt=4809600.0, new_column=10),
 Row(fromuserid=49746356, messagetype=1, dt=4809600.0, new_column=10),
 Row(fromuserid=93506471, messagetype=1, dt=4809600.0, new_column=10),
 Row(fromuserid=80488242, messagetype=1, dt=4809600.0, new_column=10)]

这非常hacky,对吧?我认为有更合法的方式来做到这一点?

最佳答案

Spark 2.2+

Spark 2.2 引入 typedLit支持Seq , Map , 和 Tuples ( SPARK-19254 ) 和以下调用应该被支持 (Scala):

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

df.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)))

Spark 1.3+ ( lit ), 1.4+ ( array , struct ), 2.0+ ( map ):
DataFrame.withColumn 的第二个参数应该是 Column所以你必须使用文字:
from pyspark.sql.functions import lit

df.withColumn('new_column', lit(10))

如果您需要复杂的列,您可以使用像 array 这样的块来构建这些列。 :
from pyspark.sql.functions import array, create_map, struct

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

关于python - 如何在 Spark DataFrame 中添加常量列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46754149/

相关文章:

python - Sklearn逻辑回归,绘制概率曲线图

python - 使用 selenium webdriver 获取浏览器版本

apache-spark - 解释 Spark Stage 输出日志

scala - Spark 输出到 kafka 恰好一次

python-3.x - 使用 apply 散列每行 Pandas 数据框列

python - Google CoLab 中的光谱 viewcube

python - 如何有效地使用多处理来加速大量的小任务?

rest - 使用 Apache Spark 查询 REST Web 服务?

r - 使用 if 将重复行压缩为唯一行

python - 将对象转换为 pandas 中的字符串后出现关键错误?