如何从带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
相关产品推荐
相关产品推荐

