详解Pandas中iloc、loc与ix索引方法的区别及用法

青禾
青禾
发布时间:2026-10-13| 4人浏览过
原创

本文详细解析Pandas库中iloc、loc及ix三种索引方法的区别。iloc仅支持整数位置索引,loc仅支持标签索引(含数字标签特殊情况),而ix为混合索引。通过代码示例展示不同标签类型下的行为差异,帮助开发者避免索引混淆,正确抽取数据。

在Pandas库中,iloc、loc以及ix均可用于数据的索引与抽取。然而,由于方法众多且功能相近,初学者容易混淆。下文将结合具体代码实例,逐一阐明它们之间的核心区别。

1. iloc与loc的核心区别

iloc方法主要依赖整数位置对数据进行索引,不支持使用字符型标签进行索引。相反,loc方法仅接受字符型标签作为索引依据,不能直接使用整数位置进行索引。但存在一种特殊情况:当DataFrame的行标签或列标签本身为数字时,loc方法也可以利用这些数字标签进行索引。

首先,通过代码演示当行标签和列标签均为数字时的情形。

import pandas as pd
import numpy as np
a = np.arange(12).reshape(3,4)
print a
>>>
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]
df = pd.DataFrame(a)
print df
>>>
 0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
print df.loc[0]
>>>
0 0
1 1
2 2
3 3
Name: 0, dtype: int32
print df.iloc[0]
0 0
1 1
2 2
3 3
Name: 0, dtype: int32
print df.loc[:,[0,3]]
 0 3
0 0 3
1 4 7
2 8 11
print df.iloc[:,[0,3]]
 0 3
0 0 3
1 4 7
2 8 11

随后,将行标签从[0, 1, 2]修改为['a', 'b', 'c'],数据框显示如下。

df.index = ['a','b','c'] 
print df 
>>> 
 0 1 2 3 
a 0 1 2 3 
b 4 5 6 7 
c 8 9 10 11 
print df.loc[0] 
# TypeError: cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <type 'int'> 
print df.iloc[0] 
>>> 
0 0 
1 1 
2 2 
3 3 
Name: a, dtype: int32 
print df.iloc['a'] # TypeError: cannot do positional indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [a] of <type 'str'> 
print df.loc['a'] # 正确 
>>> 
0 0 
1 1 
2 2 
3 3 
Name: a, dtype: int32 

同理,将列标签从[0, 1, 2, 3]修改为['A', 'B', 'C', 'D'],数据框显示如下。

df.columns = ['A','B','C','D']
print df
>>>
 A B C D
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
print df.loc[:,'A']
>>>
a 0
b 4
c 8
Name: A, dtype: int32
print df.iloc[:,'A'] # ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types

2. ix作为一种混合索引方式

print df.ix[0]
>>>
A 0
B 1
C 2
D 3
Name: a, dtype: int32
print df.ix['a']
>>>
A 0
B 1
C 2
D 3
Name: a, dtype: int32
print df.ix[:,0]
>>>
a 0
b 4
c 8
Name: A, dtype: int32
print df.ix[:,'A']
>>>
a 0
b 4
c 8
Name: A, dtype: int32

以上关于Pandas中iloc、loc以及ix区别的详细解析即为全部内容,希望能对读者有所帮助。欢迎参考,并期待大家继续支持本站。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。