【问题标题】:How to filter the dates in a pyspark dataframe如何过滤 pyspark 数据框中的日期
【发布时间】:2021-08-16 07:22:15
【问题描述】:

我有一个 pyspark 数据框:

Year    Month
2021    06/01/2021
2021    06/01/2021
2021    07/01/2021
2021    07/01/2021
2021    0/01/2021
2021    0/01/2021

我需要特定月份的数据框以及“0/01/2021”。尝试使用以下代码:

df=df.filter((col('Month')=='07/01/2021') & (col('Month')=='0/01/2021'))
display(df)

我需要的数据框是:

Year    Month
2021    07/01/2021
2021    07/01/2021
2021    0/01/2021
2021    0/01/2021

但我得到: Query returned no results 结果。 “月”列采用字符串格式。 如何过滤这些日期?

【问题讨论】:

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


    【解决方案1】:

    这很正常。您要求每一行的值都等于 07/01/2021 和 (&) 0/01/2021。
    你是什​​么月份 = 07/01/2021 OR (|) 0/01/2021:

    from pyspark.sql.functions import col
    
    a = [
        (2021, "06/01/2021"),
        (2021, "06/01/2021"),
        (2021, "07/01/2021"),
        (2021, "07/01/2021"),
        (2021, "0/01/2021"),
        (2021, "0/01/2021"),
    ]
    
    b = "Year", "Month"
    
    df = spark.createDataFrame(a, b)
    df = df.filter((col("Month") == "07/01/2021") | (col("Month") == "0/01/2021"))
    # 
    df.show()
    +----+----------+                                                               
    |Year|     Month|
    +----+----------+
    |2021|07/01/2021|
    |2021|07/01/2021|
    |2021| 0/01/2021|
    |2021| 0/01/2021|
    +----+----------+
    

    你也可以这样写:

    df.filter(col("Month").isin("07/01/2021", "0/01/2021")).show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-04
      • 2019-11-27
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多