【问题标题】:Shifting datetime index to first Monday/Tuesday/etc of next month将日期时间索引转移到下个月的第一个星期一/星期二/等
【发布时间】:2019-09-12 10:48:25
【问题描述】:

我觉得这应该是 a) 相对简单,并且 b) 已经在其他地方回答了,但我似乎无法弄清楚,几个小时的谷歌搜索让我无处可去......

我在 pandas 数据框中有一些月度数据。该索引是日期时间索引。我想将此索引移至下个月的第一个星期一/星期二/等,但我似乎不知道该怎么做...

我已经弄清楚如何分别使用 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. 

我希望得到下个月的第一个星期一或第一个星期二或第一个 ...,而不是指向下个月的第一个工作日。

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

【问题讨论】:

  • 调到第一个工作日后,再调到下周一?
  • 对。但这就是我能弄清楚该怎么做的事情。我如何告诉 shift() 去下周一?

标签: python-3.x pandas datetime


【解决方案1】:

玩过手动解决方案后,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')

【讨论】:

  • 谢谢美人!
猜你喜欢
  • 2014-02-11
  • 1970-01-01
  • 2021-09-06
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多