You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取DatetimeIndex中匹配日期的索引位置?

获取DatetimeIndex匹配日期的整数索引位置

你的DatetimeIndex示例如下:

book_df.index
Out[44]: 
DatetimeIndex(['2023-08-13 15:10:47.284558', '2023-08-13 15:10:48.005322',
               '2023-08-13 15:10:48.005953', '2023-08-13 15:10:49.022438',
               '2023-08-13 15:10:53.218365', '2023-08-13 15:10:54.246143',
               '2023-08-13 15:10:54.246874', '2023-08-13 15:10:54.247330',
               '2023-08-13 15:10:55.270271', '2023-08-13 15:10:55.270948',
               ...
               '2023-08-14 14:00:00.208915', '2023-08-14 14:00:00.209017',
               '2023-08-14 14:00:00.209119', '2023-08-14 14:00:00.209221',
               '2023-08-14 14:00:00.209323', '2023-08-14 14:00:00.209425',
               '2023-08-14 14:00:00.209527', '2023-08-14 14:00:00.209629',
               '2023-08-14 14:00:00.209730', '2023-08-14 14:00:00.209832'],
              dtype='datetime64[ns]', length=1230021, freq=None)

你当前用book_df.index == rng[0]得到布尔掩码:

Out[60]: array([ True, False, False, ..., False, False, False])

要获取具体的整数索引位置,有几种常用方法:

方法1:使用numpy.where

适合存在多个匹配的场景,返回所有满足条件的索引数组:

import numpy as np
# 获取所有匹配的索引
match_indices = np.where(book_df.index == rng[0])[0]
# 如果只需要第一个匹配的位置,取数组第一个元素
first_match_pos = match_indices[0]

方法2:使用Index.get_loc

适合确定只有一个匹配的场景,直接返回整数位置:

index_pos = book_df.index.get_loc(rng[0])

如果存在多个匹配,这个方法会抛出KeyError,此时可以改用get_indexer:

# 传入包含目标日期的列表,返回对应索引数组,无匹配则返回-1
match_indices = book_df.index.get_indexer([rng[0]])

比如你的示例中,rng[0]对应第一个元素,用上述方法都会得到0这个位置值。

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 03:34:59