如何在星火数据帧中添加一个常数列? [英] How to add a constant column in a Spark DataFrame?

查看:1766
本文介绍了如何在星火数据帧中添加一个常数列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在数据帧与一些任意值(即每一行的相同)添加一列。当我使用我得到一个错误 withColumn 如下:

I want to add a column in a DataFrame with some arbitrary value (that is the same for each row). I get an error when I use withColumn as follows:

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)将欲数:

It seems that I can trick the function into working as I want by adding and subtracting one of the other columns (so they add to zero) and then adding the number I want (10 in this case):

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)]

这是苏premely哈克,对不对?我认为还有一个更合法的方式做到这一点?

This is supremely hacky, right? I assume there is a more legit way to do this?

推荐答案

DataFrame.withColumn 第二个参数应该是一个,所以你必须使用文字:

The second argument for DataFrame.withColumn should be a Column so you have to use a literal:

from pyspark.sql.functions import lit

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

如果您需要复杂的栏,你可以建立这些使用块如阵列

If you need complex columns you can build these using blocks like array:

from pyspark.sql.functions import array, struct

df.withColumn("some_array", array(lit(1), lit(2), lit(3)))
df.withColumn("some_struct", struct(lit("foo"), lit(1), lit(.3)))

完全一样的方法可以在Scala中使用。

Exactly the same methods can be used in Scala.

import org.apache.spark.sql.functions.lit

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

另外,也可以,虽然慢,要使用UDF

It is also possible, although slower, to use an UDF.

这篇关于如何在星火数据帧中添加一个常数列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆