简体   繁体   English

在 pandas 中按月份和年份过滤 Dataframe

[英]Filter a Dataframe by months and year in pandas

I have a dataframe from which I am getting month and year values in a column like the following:我有一个 dataframe 从中获取月份和年份值,如下所示:

temp dd   delivery_month       
0        02-2021      #mm-yyyy
1        01-2021      
2        02-2021  
3        02-2021  

I want to use the month and year from all of the rows in that column to filter another dataframe but I got the following error:我想使用该列中所有行的月份和年份来过滤另一个 dataframe 但我收到以下错误:

Can only use.dt accessor with datetimelike values只能使用带有 datetimelike 值的 .dt 访问器

The date in the second dataframe is like the following:第二个 dataframe 中的日期如下:

 allot_df['dispatch_date'][0]   06-01-2020

I tried the following but it doesn't work我尝试了以下但它不起作用

    for row in temp_dd.itertuples():

        allot_df = allot_df[allot_df['dispatch_date'].dt.month == row.delivery_month[:2]]

where temp_dd is the first dataframe其中temp_dd是第一个 dataframe

How can I filter the allot_df dataframe by both month and year from temp_dd ?如何从 temp_dd 按月和年过滤allot_df temp_dd

I think problem is values not datetimes, if format mm-YYYY use:我认为问题是值而不是日期时间,如果格式mm-YYYY使用:

allot_df['dispatch_date'] = pd.to_datetime(allot_df['dispatch_date'], format='%m-%Y')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM