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

发布于 2021-02-02 23:14:07

我想在中添加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)]

这绝对是骇客,对吧?我认为还有一种更合法的方法吗?

关注者
0
被浏览
98
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    Spark 2.2+

    Spark 2.2引入typedLitsupport SeqMapTuples(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)))
    星火1.3+(lit),1.4+(array,struct),2.0+(map):
    

    的第二个参数DataFrame.withColumn应该是aColumn因此你必须使用文字:

    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

    注意事项:

    可以使用相同的构造将常量参数传递给UDFSQL函数。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看