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

Pandas中以日期时间为索引的DataFrame如何获取指定日期对应行号

Pandas Datetime索引匹配行号最优实现方案

不需要新增冗余计数列、无需修改原DataFrame,性能远高于你当前的实现方式,推荐以下几种适配不同场景的写法:

方法1:索引原生get_loc方法(索引值唯一时首选)

pandas索引内置的标签定位接口,时间复杂度最低,代码最简洁:

import pandas as pd
from datetime import datetime

sdate = datetime(2021,6,5,14)  # 起始时间
edate = datetime(2021,6,30)   # 结束时间
date_to_find = datetime(2021,6,25,16)
df = pd.DataFrame(index=pd.date_range(sdate, edate, freq='H'))

# 一行代码直接获取对应行号
row_num = df.index.get_loc(date_to_find)

说明:如果索引存在重复的相同时间值,get_loc会返回布尔掩码或切片对象,这种场景推荐使用方法2

方法2:numpy.where匹配(支持重复索引场景)

如果索引存在多个相同时间值,可以一次性返回所有匹配的行号数组:

import numpy as np

# 返回所有符合条件的行号数组
match_row_nums = np.where(df.index == date_to_find)[0]
# 取第一个匹配的行号
row_num = match_row_nums[0]

方法3:Index.get_indexer(批量匹配多日期场景)

如果需要同时匹配多个目标日期的行号,用这个方法批量查询效率更高:

# 待匹配的多个日期
dates_to_find = [datetime(2021,6,25,16), datetime(2021,6,26,8), datetime(2021,6,27,12)]
# 批量返回对应行号数组
row_nums = df.index.get_indexer(dates_to_find)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:06:08