明月笑刀无情
想法是从 开始按季度创建字典February,然后Series.map按月份使用并按boolean indexing日期时间过滤now从字典转换为您的季度dq:q = [[2,3,4],[5,6,7],[8,9,10],[11,12,1]]dq = {x: k for k, v in enumerate(q, 1) for x in v}print (dq){2: 1, 3: 1, 4: 1, 5: 2, 6: 2, 7: 2, 8: 3, 9: 3, 10: 3, 11: 4, 12: 4, 1: 4}now = dq[pd.to_datetime('now').month]print (now)3df1 = df[df['Month'].map(dq) == now]print (df1) Quarter Month Data Value7 3 8 H 1128 3 9 I 1879 4 10 J 132如果需要按其他日期时间过滤:date = datetime.date(2015, 1, 13)now = dq[date.month]print (now)4df1 = df[df['Month'].map(dq) == now]print (df1) Quarter Month Data Value0 1 1 A 10010 4 11 K 10911 4 12 L 121编辑:在上面的解决方案中不区分年份和季度,因此为其添加了新的解决方案tseries.offsets.QuarterBegin:#add year columnprint (df) Quarter Month Data Value Year0 1 1 A 100 20201 1 2 B 134 20202 1 3 C 145 20203 2 4 D 156 20204 2 5 E 167 20205 2 6 F 178 20206 3 7 G 123 20207 3 8 H 112 20208 3 9 I 187 20209 4 10 J 132 202010 4 11 K 109 202011 4 12 L 121 2020#convert columns to datetimes and convert to datetime for start oq quarterdf['Q'] = (pd.to_datetime(df[['Month','Year']].assign(Day=1)) + pd.offsets.QuarterBegin(0, startingMonth=2))print (df) Quarter Month Data Value Year Q0 1 1 A 100 2020 2020-02-011 1 2 B 134 2020 2020-02-012 1 3 C 145 2020 2020-05-013 2 4 D 156 2020 2020-05-014 2 5 E 167 2020 2020-05-015 2 6 F 178 2020 2020-08-016 3 7 G 123 2020 2020-08-017 3 8 H 112 2020 2020-08-018 3 9 I 187 2020 2020-11-019 4 10 J 132 2020 2020-11-0110 4 11 K 109 2020 2020-11-0111 4 12 L 121 2020 2021-02-01还被添加QuarterBegin到日期时间和最后的拟合器中:date = datetime.date(2020, 1, 13)custom_q = (date + pd.offsets.QuarterBegin(0, startingMonth=2))print (custom_q)2020-02-01 00:00:00df1 = df[df['Q'] == custom_q]print (df1) Quarter Month Data Value Year Q0 1 1 A 100 2020 2020-02-011 1 2 B 134 2020 2020-02-01