将日期时间索引移至下个月的第一个星期一/星期二/等



我觉得这应该是 a( 相对简单,b( 已经在其他地方回答了,但我似乎想不通,几个小时的谷歌搜索让我无处可去......

我在熊猫数据帧中有一些每月数据。该索引是日期时间索引。我想将此指数转移到下个月的第一个星期一/星期二/等,但我似乎不知道该怎么做......

我已经弄清楚了如何使用 shift(( 方法分别使用 freq='BMS' 和 freq='BM' 切换到该月的第一个工作日和最后一个工作日。但是,我不知道如何从那里开始。下面写了一个移动数据索引的示例:

#setting up an arbitrary example df with a similar datetime index:
date_rng = pd.date_range(start='1/1/1950', end='1/08/1955', freq='MS').shift(14, freq='D')
test_df = pd.DataFrame(range(len(date_rng)), index=date_rng, columns=['ticker_name'])
#what I know how to do so far
rng_index = test_df.index
new_range = rng_index.shift(1, freq='BMS') #first business day of month (use 'BM' for last business day of month
test_df.index = new_range #My df should now have a new index pointing to the first business day of the next month. 

与其指向下个月的第一个工作日,我想得到第一个星期一或第一个星期二或第一个......下个月。

非常感谢任何和所有的帮助! 干杯

使用手动解决方案后,似乎pandas有一个内置解决方案:

date_rng = pd.date_range(start='1/1/1950', end='1/08/1955', freq='MS').shift(14, freq='D')
date_rng.shift(1, freq='WOM-1MON')

输出似乎是正确的:

DatetimeIndex(['1950-02-06', '1950-03-06', '1950-04-03', '1950-05-01',
'1950-06-05', '1950-07-03', '1950-08-07', '1950-09-04',
'1950-10-02', '1950-11-06', '1950-12-04', '1951-01-01',
'1951-02-05', '1951-03-05', '1951-04-02', '1951-05-07',
'1951-06-04', '1951-07-02', '1951-08-06', '1951-09-03',
'1951-10-01', '1951-11-05', '1951-12-03', '1952-01-07',
'1952-02-04', '1952-03-03', '1952-04-07', '1952-05-05',
'1952-06-02', '1952-07-07', '1952-08-04', '1952-09-01',
'1952-10-06', '1952-11-03', '1952-12-01', '1953-01-05',
'1953-02-02', '1953-03-02', '1953-04-06', '1953-05-04',
'1953-06-01', '1953-07-06', '1953-08-03', '1953-09-07',
'1953-10-05', '1953-11-02', '1953-12-07', '1954-01-04',
'1954-02-01', '1954-03-01', '1954-04-05', '1954-05-03',
'1954-06-07', '1954-07-05', '1954-08-02', '1954-09-06',
'1954-10-04', '1954-11-01', '1954-12-06', '1955-01-03',
'1955-02-07'],
dtype='datetime64[ns]', freq='WOM-1MON')

最新更新