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

如何从带DateTimeIndex的过滤后pandas DataFrame中获取整数索引值

解决方案

针对带DateTimeIndex的pd.DataFrame,筛选后获取结果对应原始数据的整数行索引(从0开始计数),可以用以下两种方法实现:

方法1:基于筛选结果反向查询

在得到筛选后的df_selection后,直接调用原始索引的get_indexer方法获取对应位置:

# 接你提供的示例代码
result = df.index.get_indexer(df_selection.index).tolist()
print(result)
# 输出:[2, 3]

方法2:过滤时直接获取整数索引

无需提前生成筛选后的DataFrame,写过滤条件时直接匹配得到行号:

import numpy as np
target_dates = pd.date_range(start="2021-01-02", periods=2)
result = np.where(df.index.isin(target_dates))[0].tolist()
print(result)
# 输出:[2, 3]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:24:04