如何根据给定的日期从 DatetimeIndex 获取索引计数?

tho*_*3ch 5 python-3.x

我有一个 DataFrame,它的索引是 DatetimeIndex 类型,如下所示:

DatetimeIndex(
    ['2003-10-17', '2003-10-21', '2003-10-22', '2003-10-23',
      '2003-10-24', '2003-10-27', '2003-10-28', '2003-10-29',
      '2003-10-30', '2003-10-31',
       ...
      '2017-08-04', '2017-08-07', '2017-08-08', '2017-08-09',
      '2017-08-10', '2017-08-11', '2017-08-14', '2017-08-15',
      '2017-08-16', '2017-08-17'
    ],
    dtype='datetime64[ns, UTC]', name=u'DATE', length=3482, freq=None
)
Run Code Online (Sandbox Code Playgroud)

2017-08-04我想知道如何获取例如索引计数的位置。

Rom*_*est 7

要仅获取键的整数位置,'2017-08-04'请使用DatetimeIndex.get_loc函数:

dt_idx = pd.DatetimeIndex(
    [ '2003-10-17', '2003-10-21', '2003-10-22', '2003-10-23', '2003-10-24', '2003-10-27',
      '2003-10-28', '2003-10-29', '2003-10-30', '2003-10-31', '2017-08-04', '2017-08-07',
      '2017-08-08', '2017-08-09', '2017-08-10', '2017-08-11', '2017-08-14', '2017-08-15',
      '2017-08-16', '2017-08-17'
     ], dtype='datetime64[ns, UTC]', name=u'DATE', length=3482, freq=None)

print(dt_idx.get_loc('2017-08-04'))
Run Code Online (Sandbox Code Playgroud)