簡體   English   中英

如何過濾pyspark dataframe中的日期

[英]How to filter the dates in a pyspark dataframe

我有一個 pyspark dataframe:

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

我需要特定月份的 dataframe 以及“0/01/2021”。 嘗試使用以下代碼:

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

我需要的 dataframe 是:

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

但我得到: Query returned no results “月份”列采用字符串格式。 如何過濾這些日期?

這很正常。 您要求每一行的值都等於 07/01/2021 AND ( & ) 0/01/2021。
你是什么行,其中 month = 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM