首页 > 解决方案 > Pandas:如何选择本月和最近两个月的值?

问题描述

我有一个包含以下列但没有 NaN 的多年财务预算数据的数据框:

Index
Dates (datetime) with data for each day of the month
Category (object) with several different names
Amount (float) in USD

我将如何声明“本月”值,然后过滤数据框以查找“本月”和“上个月”或“两个月”前之间的所有值?

标签: pythonpandasdataframedatetimetimedelta

解决方案


您可以使用datetime模块中的 .today() 方法获取实际时间戳,然后应用 .month 将月份提取为“int”。您也可以使用 .month 进行过滤:

import datetime as dt

this_month = dt.datetime.today().month
two_months_ago = this_month - 2 if this_month - 2 > 0 else this_month - 2 + 12
filter = df['Dates'].dt.month == two_month_ago

推荐阅读