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

Pandas .iloc API索引规则疑问:取0-9列为何需用0:10?

关于pandas中.iloc索引规则的疑问

数据集信息

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 400 entries, 0 to 399
Data columns (total 11 columns):
 #   Column       Non-Null Count  Dtype 
---  ------       --------------  ----- 
 0   CompPrice    400 non-null    int64 
 1   Income       400 non-null    int64 
 2   Advertising  400 non-null    int64 
 3   Population   400 non-null    int64 
 4   Price        400 non-null    int64 
 5   ShelveLoc    400 non-null    object
 6   Age          400 non-null    int64 
 7   Education    400 non-null    int64 
 8   Urban        400 non-null    object
 9   US           400 non-null    object
 10  HighSales    400 non-null    object
dtypes: int64(7), object(4)
memory usage: 34.5+ KB

疑问描述

从上述结果可知,DF共有11列,列索引为0至10。想要提取前10列(即索引0到9的列),但使用代码DF.iloc[:, 0:9]时,仅返回前9列(从CompPrice到Urban);改为DF.iloc[:, 0:10]才能得到预期的前10列(从CompPrice到US)。困惑点在于:为何起始用0,结束却要用10而非9,起始与结束索引规则似乎不一致?


解答

这是因为pandas的.iloc采用左闭右开的索引规则,也就是区间包含起始索引对应的元素,但不包含结束索引对应的元素。

举个直观的例子:

  • 用0:9时,实际包含的是索引0、1、2……8的元素,一共9个;
  • 用0:10时,包含的是索引0、1、2……9的元素,正好10个,也就是你需要的前10列。

这种规则和Python原生的切片逻辑完全一致,比如对列表[0,1,2,3,4]做[0:3]切片,得到的是[0,1,2],同样是包含起始位、不包含结束位。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 02:16:34