根据日期过滤熊猫

时间:2020-10-22 10:08:24

标签: python pandas date jupyter-notebook jupyter

我正在通过选择日期范围来将熊猫分为不同的部分。

我在线找到了以下解决方案,但它忽略了我指定的年份。相反,它为我提供了指定日期之间的所有条目,即使我(在此示例中)仅想要2020年的条目。有什么想法吗?

我有什么

start_date = "10/12/2020"
end_date = "10/15/2020"

after_start_date = df["Timestamp"] >= start_date
before_end_date = df["Timestamp"] <= end_date
between_two_dates = after_start_date & before_end_date
filtered_dates = df.loc[between_two_dates]
filtered_dates

我能得到的


1   10/14/2020 
2   10/13/2020
3   10/12/2020
262 10/15/2019
263 10/14/2019
523 10/15/2018
784 10/13/2017
1044    10/14/2016
1045    10/13/2016 
etc.
 

我想要的

1   10/15/2020 
2   10/14/2020 
3   10/13/2020 
4   10/12/2020  
 
  

1 个答案:

答案 0 :(得分:1)

似乎您的数据未转换为日期时间:

df['Timestamp'] = pd.to_datetime(df['Timestamp'], dayfirst=True)

#default datetime format with YYYY-MM-DD
start_date = "2020-10-12"
end_date = "2020-10-15"

after_start_date = df["Timestamp"] >= start_date
before_end_date = df["Timestamp"] <= end_date
between_two_dates = after_start_date & before_end_date
filtered_dates = df.loc[between_two_dates]

print (filtered_dates)
   Timestamp
1 2020-10-14
2 2020-10-13