【问题标题】:Partition of Timestamp column in Dataframes PysparkDataframes Pyspark 中时间戳列的分区
【发布时间】:2017-06-03 08:32:38
【问题描述】:

我在 PSspark 中有一个DataFrame,格式如下

Date        Id  Name    Hours   Dno Dname
12/11/2013  1   sam     8       102 It
12/10/2013  2   Ram     7       102 It
11/10/2013  3   Jack    8       103 Accounts
12/11/2013  4   Jim     9       101 Marketing

我想根据dno 进行分区,并使用 Parquet 格式保存为 Hive 中的表。

df.write.saveAsTable(
    'default.testing', mode='overwrite', partitionBy='Dno', format='parquet')

查询运行良好,并在 Hive 中使用 Parquet 输入创建了表。

现在我想根据日期列的年份和月份进行分区。时间戳为 Unix 时间戳

我们如何在 PySpark 中实现这一点。我已经在 hive 中完成了,但 PySpark 无法做到

【问题讨论】:

    标签: apache-spark dataframe timestamp pyspark partition


    【解决方案1】:

    火花 >= 3.1

    timestamp_seconds代替cast

    from pyspark.sql.functions import timestamp_seconds
    
    year(timestamp_seconds(col("timestamp")))
    

    火花

    只需提取您要使用的字段,并将列列表作为参数提供给作者的partitionBy。如果timestamp 是以秒表示的 UNIX 时间戳:

    df = sc.parallelize([
        (1484810378, 1, "sam", 8, 102, "It"),
        (1484815300, 2, "ram", 7, 103, "Accounts")
    ]).toDF(["timestamp", "id", "name", "hours", "dno", "dname"])
    

    添加列:

    from pyspark.sql.functions import year, month, col
    
    df_with_year_and_month = (df
        .withColumn("year", year(col("timestamp").cast("timestamp")))
        .withColumn("month", month(col("timestamp").cast("timestamp"))))
    

    然后写:

    (df_with_year_and_month
        .write
        .partitionBy("year", "month")
        .mode("overwrite")
        .format("parquet")
        .saveAsTable("default.testing"))
    

    【讨论】:

    • 我尝试了您的技术按小时分区然后写入镶木地板: df.write.partitionBy('hour').parquet(path) 但是,尽管 df 中至少有 10 个独特的小时,我只得到 2 部分镶木地板 - 你能帮忙解释一下吗?谢谢!
    • @Davos 不是真正的技巧,而是PEP8 推荐“包装长行的首选方法是在括号、方括号和大括号内使用 Python 隐含的行继续。长行可以在多行上断开通过将表达式包装在括号中。应该优先使用这些表达式,而不是使用反斜杠来续行。"
    猜你喜欢
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2019-05-14
    • 2020-08-29
    相关资源
    最近更新 更多