我想在 DataFrame
中添加一个具有一些任意值的列(对于每一行都是相同的) . 我使用_1172303时出现错误,如下所示:
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,对吗?我假设有更合法的方法来做到这一点?
2 回答
Spark 2.2+
Spark 2.2引入
typedLit
以支持Seq
,Map
和Tuples
(SPARK-19254),并且应支持以下调用(Scala):Spark 1.3+ (
lit
), 1.4+ (array
,struct
), 2.0+ (map
):DataFrame.withColumn
的第二个参数应为Column
,因此您必须使用文字:如果您需要复杂的列,可以使用
array
之类的块构建这些列:在Scala中可以使用完全相同的方法 .
要为
structs
提供名称,请在每个字段上使用alias
:或
cast
整个对象尽管速度较慢,但使用UDF也是可能的 .
Note :
可以使用相同的构造将常量参数传递给UDF或SQL函数 .
在spark 2.2中,有两种方法可以在DataFrame的列中添加常量值:
1)使用
lit
2)使用
typedLit
.两者之间的区别在于
typedLit
也可以处理参数化的scala类型,例如列表,序列和 MapSample DataFrame:
1) Using lit: 在名为newcol的新列中添加常量字符串值:
结果:
2) Using typedLit:
结果: