如何让Pandas知道节日的日期?

2024-04-24 06:08:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在看文档here

我有一个包含每日时间序列的数据帧(请注意,2013-03-29是一个假日,mydf包含2013-03-28)。在

import pandas as pd

business_month_end_dates = pd.date_range('2010-01-31', '2014-04-30', freq='BM')

business_month_end_dates

DatetimeIndex(['2010-02-26', '2010-03-31', '2010-04-30', '2010-05-31',
           '2010-06-30', '2010-07-30', '2010-08-31', '2010-09-30',
           '2010-10-29', '2010-11-30', '2010-12-31', '2011-01-31',
           '2011-02-28', '2011-03-31', '2011-04-29', '2011-05-31',
           '2011-06-30', '2011-07-29', '2011-08-31', '2011-09-30',
           '2011-10-31', '2011-11-30', '2011-12-30', '2012-01-31',
           '2012-02-29', '2012-03-30', '2012-04-30', '2012-05-31',
           '2012-06-29', '2012-07-31', '2012-08-31', '2012-09-28',
           '2012-10-31', '2012-11-30', '2012-12-31', '2013-01-31',
           '2013-02-28', '2013-03-29', '2013-04-30', '2013-05-31',
           '2013-06-28', '2013-07-31', '2013-08-30', '2013-09-30',
           '2013-10-31', '2013-11-29', '2013-12-31', '2014-01-31',
           '2014-02-28', '2014-03-31', '2014-04-30'],
          dtype='datetime64[ns]', freq='BM')

然后创建业务年度结束日期:

^{pr2}$

我的预期产出是:

DatetimeIndex(['2010-03-31', '2011-03-31', '2012-03-30', '2013-03-28',
       '2014-03-31'],
      dtype='datetime64[ns]', freq='BA-MAR')

熊猫是否应该通过BM business month end frequency来理解2013-03-29是一个假日?在

如果没有,我如何让熊猫意识到当我使用BM时,它使用的是前一个工作日(在本例中为2013-03-28)?在


Tags: 文档here时间序列businessbmendpd
1条回答
网友
1楼 · 发布于 2024-04-24 06:08:58

试试这样的方法:

import numpy as np
import pandas as pd
from pandas.tseries.offsets import CustomBusinessMonthEnd

index = pd.date_range('2010-01-31', '2014-04-30', freq='BM')
df = pd.DataFrame(data=np.random.rand(len(index), 2), columns=['a', 'b'], index=index)

holidays = ['2013-03-29']

df = df.resample(rule=CustomBusinessMonthEnd(holidays=holidays)).last()

df = df.loc[df.index.month==3]

输出:

^{pr2}$

相关问题 更多 >