Python 3.x 根据数据中的特定年份和月份从多个日期列中筛选行

Python 3.x 根据数据中的特定年份和月份从多个日期列中筛选行,python-3.x,pandas,dataframe,datetime,Python 3.x,Pandas,Dataframe,Datetime,对于给定的数据帧,如下所示: id start_date end_date 0 1 2014/5/26 2014/5/27 1 2 2014/6/27 2014/6/28 2 3 2014/7/20 2014/7/21 3 4 2014/9/12 2014/9/13 4 5 2014/10/10 2014/10/11 5 6 2020/3/20 2020/4/21 6 7 2020/4/10 2020/

对于给定的数据帧,如下所示:

   id  start_date    end_date
0   1   2014/5/26   2014/5/27
1   2   2014/6/27   2014/6/28
2   3   2014/7/20   2014/7/21
3   4   2014/9/12   2014/9/13
4   5  2014/10/10  2014/10/11
5   6   2020/3/20   2020/4/21
6   7   2020/4/10   2020/4/11
7   8   2020/4/15   2020/4/16
8   9   2020/3/23   2020/3/24
9  10    2020/4/6    2020/4/7
我想筛选
start\u date
end\u date
2020-02、2020-03、2020-04
范围内的行,感谢分享除我之外的其他可选解决方案

查找转发结果如下所示:

   id start_date   end_date
5   6 2020-03-20 2020-04-21
6   7 2020-04-10 2020-04-11
7   8 2020-04-15 2020-04-16
9  10 2020-04-06 2020-04-07

以下解决方案有效:

df[['start_date', 'end_date']] = df[['start_date', 'end_date']].applymap(lambda x: pd.to_datetime(x, format = '%Y/%m/%d'))
df.loc[((df['start_date'].dt.year == 2020) & (df['start_date'].dt.month==4)) | ((df['end_date'].dt.year == 2020) & (df['end_date'].dt.month==4))]
输出:

我认为按列处理更好,按元素处理更好:

df[['start_date', 'end_date']] = (df[['start_date', 'end_date']]
                                   .apply(lambda x: pd.to_datetime(x, format = '%Y/%m/%d')))
然后,用于过滤的时间段由以下人员使用:

可以使用按列循环的解决方案,如果列数更多,则解决方案更好:

c = ['start_date', 'end_date']
df[c] = df[c].apply(lambda x: pd.to_datetime(x, format = '%Y/%m/%d'))

df = df[np.logical_or.reduce([df[x].dt.to_period('m')== '2020-04' for x in c])]
print (df)
   id start_date   end_date
5   6 2020-03-20 2020-04-21
6   7 2020-04-10 2020-04-11
7   8 2020-04-15 2020-04-16
9  10 2020-04-06 2020-04-07

谢谢,如果我需要按多个月进行筛选,例如
2020-02、2020-03、2020-04
?我的解决方案需要添加太多代码。@ahbon-我认为这里应该使用
isin
,尝试
L=[pd.Period('2020-03')、pd.Period('2020-05')]df=(df[(df['start_date'].dt.to_Period('m').isin(L))(df['end_date'].dt to_Period('m').isin(L))
我使用
L=[pd.Period('2019-10')、pd.Period('2019-11')),pd.Period('2019-12')]
过滤2019年第四季度的数据,但8月份的数据在里面,有什么想法吗?@ahbon-我明白了,
isin
就像
,但你想要
。给我一些time@ahbon-但如果需要
则可以使用
df=df[np.logical_和.reduce([(df['start_date'].dt.to_period('m').eq(x))|(df['end_date'].dt.to_period('m').eq(x))表示L中的x])
df = (df[(df['start_date'].dt.to_period('m')== '2020-04') | 
         (df['end_date'].dt.to_period('m')== '2020-04')])
print (df)
   id start_date   end_date
5   6 2020-03-20 2020-04-21
6   7 2020-04-10 2020-04-11
7   8 2020-04-15 2020-04-16
9  10 2020-04-06 2020-04-07
c = ['start_date', 'end_date']
df[c] = df[c].apply(lambda x: pd.to_datetime(x, format = '%Y/%m/%d'))

df = df[np.logical_or.reduce([df[x].dt.to_period('m')== '2020-04' for x in c])]
print (df)
   id start_date   end_date
5   6 2020-03-20 2020-04-21
6   7 2020-04-10 2020-04-11
7   8 2020-04-15 2020-04-16
9  10 2020-04-06 2020-04-07