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

如何基于索引数组筛选Python Pandas DataFrame?

问题解决:DataFrame按位置索引筛选记录触发KeyError的处理

问题场景

现有DataFrame X:

In [29]: X
Out[29]: 
         RepID
76758   207355
5787     15900
101140  273993
96040   260308
82096   221946
65858   178020
40664   109821
56044   151664
76522   206735
12478    33774

另有位置索引数组test_indices:

In [30]: test_indices
Out[30]: array([7, 8])

执行X_test = X[test_indices]时触发错误:

KeyError: "None of [Index([7, 8], dtype='int32')] are in the [columns]"

原因分析

Pandas中直接用X[xxx]默认是按列名筛选,你传入的[7,8]不是DataFrame的列名(仅存在RepID列),因此触发KeyError。你实际需要筛选的是第8、第9行(位置索引从0开始计数),属于行位置索引,而非DataFrame的自定义索引值。

解决方法

  • 使用iloc方法(推荐,语义明确)

    X_test = X.iloc[test_indices]
    

    iloc是Pandas专门用于整数位置索引的方法,精准匹配你提取第7、8位(0起始)行数据的需求。

  • 使用take方法

    X_test = X.take(test_indices)
    

    take方法可直接传入位置索引数组,提取对应位置的行记录。

执行结果

上述方法执行后,X_test将得到:

RepID
56044   151664
76522   206735

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 05:33:14