mysql新增一个常数列_如何在星火数据帧中添加一个常数列?

bd96500e110b49cbb3cd949968f18be7.png

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)

in ()

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'

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

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

解决方案

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

Exactly the same methods can be used in Scala.

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值