Pandas:如何选择本月和最近两个月的值?

问题描述 投票:0回答:2

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

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

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

python pandas dataframe datetime timedelta
2个回答
0
投票

您可以使用 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

0
投票

您还可以使用重新采样方法

import pandas as pd
# Use 'ME' for resampling data by month
for month, month_df in df.resample('ME'):
    print(f"Month: {month}")
    print(month_df)
© www.soinside.com 2019 - 2024. All rights reserved.