【问题标题】:Filter spark dataframe based on previous month and year根据上个月和年份过滤火花数据框
【发布时间】:2021-03-01 06:40:31
【问题描述】:

我有以下 spark 数据帧/数据集。

Column_A   Column_B
2020-12-31 1
2020-11-02 2
2020-10-01 3
2021-02-01 4
2021-01-05 5
2021-02-10 6
2021-02-11 7
2021-02-26 8
2021-03-01 9

我必须过滤并仅保留从脚本执行之日起属于上个月的那些记录。

假设我在 2021 年 1 月 1 日执行 spark 程序,输出数据帧应该只有 2020 年 12 月的记录。如果我今天(3 月 1 日)执行它,那么它应该返回 2021 年 2 月的所有行。

预期输出:

Column_A   Column_B
2021-02-01 4
2021-02-10 6
2021-02-11 7
2021-02-26 8

如何在 pyspark 中实现这一点。

【问题讨论】:

    标签: dataframe apache-spark pyspark apache-spark-sql


    【解决方案1】:

    您可以使用current_dateadd_months 函数进行过滤:

    from pyspark.sql import functions as F
    
    df1 = df.filter(
        (F.month(F.col("Column_A")) == F.month(F.add_months(F.current_date(), -1))) &
        (F.year(F.col("Column_A")) == F.year(F.add_months(F.current_date(), -1)))
    )
    
    df1.show()
    #+----------+--------+
    #|  Column_A|Column_B|
    #+----------+--------+
    #|2021-02-01|       4|
    #|2021-02-10|       6|
    #|2021-02-11|       7|
    #|2021-02-26|       8|
    #+----------+--------+
    

    使用date_format

    df1 = df.filter(
        F.date_format(F.col("Column_A"), "yyyyMM") == F.date_format(F.add_months(F.current_date(), -1), "yyyyMM")
    )
    

    使用date_trunc

    df1 = df.filter(
        F.date_trunc("month", F.col("Column_A")) == F.date_trunc("month", F.add_months(F.current_date(), -1))
    )
    

    【讨论】:

      猜你喜欢
      • 2021-11-25
      • 2015-11-06
      • 2018-11-23
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多