Tôi muốn thêm cột vào một số DataFrame
với một số giá trị tùy ý (giống nhau cho mỗi hàng). Tôi nhận được một lỗi khi tôi sử dụng withColumn
như sau:Làm thế nào để thêm một cột không đổi trong một DataFrame Spark?
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'
Dường như tôi có thể đánh lừa các chức năng vào làm việc như tôi muốn bằng cách thêm và trừ đi một trong những cột khác (do đó họ thêm vào zero) và sau đó thêm số tôi muốn (10 trong trường hợp này):
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)]
Điều này cực kỳ đáng sợ, phải không? Tôi cho rằng có một cách hợp pháp hơn để làm điều này?
ai xuống bình chọn nó vui lòng cung cấp một lời giải thích. –