首页 文章

根据日期过滤火花数据帧

提问于
浏览
18

我有一个数据帧

date, string, string

我想在某段时间之前选择日期 . 我试过以下没有运气

data.filter(data("date") < new java.sql.Date(format.parse("2015-03-14").getTime))

我收到一条错误说明以下内容

org.apache.spark.sql.AnalysisException: resolved attribute(s) date#75 missing from date#72,uid#73,iid#74 in operator !Filter (date#75 < 16508);

据我所知,查询不正确 . 任何人都可以告诉我应该格式化查询的方式?

我检查了数据框中的所有企业都有值 - 他们这样做了 .

2 回答

  • 1

    spark 1.5 以来,以下解决方案适用:

    低于:

    // filter data where the date is lesser than 2015-03-14
    data.filter(data("date").lt(lit("2015-03-14")))
    

    大于:

    // filter data where the date is greater than 2015-03-14
    data.filter(data("date").gt(lit("2015-03-14")))
    

    为了相等,您可以使用 equalTo===

    data.filter(data("date") === lit("2015-03-14"))
    

    如果 DataFrame 日期列的类型为 StringType ,则可以使用 to_date 函数进行转换:

    // filter data where the date is greater than 2015-03-14
    data.filter(to_date(data("date")).gt(lit("2015-03-14")))
    

    您还可以使用 year 函数根据年份进行过滤:

    // filter data where year is greater or equal to 2016
    data.filter(year($"date").geq(lit(2016)))
    
  • 34

    在PySpark(python)中,其中一个选项是使列为unix_timestamp格式 . 我们可以将字符串转换为unix_timestamp并指定格式,如下所示 . 注意我们需要导入unix_timestamp和lit函数

    from pyspark.sql.functions import unix_timestamp, lit
    
    df.withColumn("tx_date", to_date(unix_timestamp(df_cast["date"], "MM/dd/yyyy").cast("timestamp")))
    

    现在我们可以应用过滤器了

    df_cast.filter(df_cast["tx_date"] >= lit('2017-01-01')) \
           .filter(df_cast["tx_date"] <= lit('2017-01-31')).show()
    

相关问题