Python Pandas DataFrame索引与数据选取详解

陆遥
陆遥
发布时间:2026-10-15| 4人浏览过
原创

本文详细解析Python Pandas中DataFrame的索引机制,涵盖行索引与列索引的定义及自定义方法。重点介绍通过方括号、.loc()及.iloc()进行单列、多列及特定行数据的选取技巧,区分Series与DataFrame返回类型,帮助开发者高效处理表格数据。

1.索引是什么

1.1 认识索引

首先构建一个基础的DataFrame实例。

myList = [['a', 10, 1.1],
	  ['b', 20, 2.2],
	  ['c', 30, 3.3],
	  ['d', 40, 4.4]]
df1 = pd.DataFrame(data = myList)
print(df1)
--------------------------------
[out]:
   0   1    2
0  a  10  1.1
1  b  20  2.2
2  c  30  3.3
3  d  40  4.4

在DataFrame结构中,存在两类核心索引:

  • 行索引(index):位于表格最左侧的垂直列。
  • 列索引(columns):位于表格最上方的水平行。

默认情况下,这两类索引均使用从0开始的自增整数序列。

# 输出行索引
print(df1.index)
[out]:
RangeIndex(start=0, stop=4, step=1)
---------------------------------------
# 输出列索引
print(df1.columns)
[out]:
RangeIndex(start=0, stop=3, step=1)
---------------------------------------
# 输出所有的值
print(df1.values)
[out]:
array([['a', 10, 1.1],
       ['b', 20, 2.2],
       ['c', 30, 3.3],
       ['d', 40, 4.4]], dtype=object)

1.2 自定义索引

可以通过index参数指定行索引,利用columns参数指定列索引。

df2 = pd.DataFrame(myList, 
		           index = ['one', 'two', 'three', 'four'], 
		           columns = ['char', 'int', 'float'])
print(df2)
-----------------------------------------------------------
[out]:
      char  int  float
one      a   10    1.1
two      b   20    2.2
three    c   30    3.3
four     d   40    4.4

查看当前的行索引与列索引结果:

# 输出行索引 print(df2.index) [out]: Index(['one', 'two', 'three', 'four'], dtype='object') -------------------------------------------------------- # 输出列索引 print(df2.columns) [out]: Index(['char', 'int', 'float'], dtype='object')

2. 索引的简单使用

2.1 列索引

选取单个列的方法如下:

print(df2['char'])
print(df2.char)
# 两种方式输出一样
[out]:
one      a
two      b
three    c
four     d
Name: char, dtype: object

需注意,当方括号内仅传入单个字符串'char'时,返回结果的类型为Series。

print(df2['char'])
print(df2.char)
# 两种方式输出一样
[out]:
one      a
two      b
three    c
four     d
Name: char, dtype: object

选取多个列的方法如下:

print(df2[['char', 'int']])
[out]: 
      char   int
one      a   10
two      b   20
three    c   30
four     d   40

当方括号内传入列表['char', 'int']时,返回结果的类型为DataFrame。若希望仅选取一列但强制返回DataFrame类型,应如何处理?

print(df2[['char']])
[out]:
      char
one      a
two      b
three    c
four     d
---------------------------------------
type(df2[['char']])
[out]:pandas.core.frame.DataFrame

直接执行df2[0]选取某一列会引发报错,除非columns是由下标索引组成(如df1的情况),否则df1[0]不会报错。

print(df1[0])
[out]:
0    a
1    b
2    c
3    d
Name: 0, dtype: object
-----------------------
print(df2[0])
[out]: 
KeyError: 0

2.2 行索引

2.2.1 使用[ ]

与选取列不同,此方式下的[ ]内需使用冒号进行切片操作,而非单独传入字符串。

选取行标签从'two'到'three'的多行数据。

print(df2['two': 'three'])
[out]:
      char  int  float
two      b   20    2.2
three    c   30    3.3

选取行标签为'two'的单一行数据。

# 此时返回的类型为DataFrame
print(df2['two': 'two'])
[out]:
      char  int  float
two      b   20    2.2

在[ ]中,除了传入行标签,还可以传入行的编号。

选取从第1行到第3行的数据(编号从0开始)。

print(df2[1:4])
[out]:
      char  int  float
two      b   20    2.2
three    c   30    3.3
four     d   40    4.4

观察可知,选取的数据不包含方括号最右侧编号所对应的数据。

选取第1行的数据。

print(df2[1:2])
[out]:
    char  int  float
two    b   20    2.2

2.2.2 使用.loc()和.iloc()

两者的区别在于:.loc()依据行索引和列索引的值来选取数据,而.iloc()依据从0开始的下标位置进行索引。

选取行的操作示例:

使用.loc()方法。

print(df2.loc['one'])
[out]:
char       a
int       10
float    1.1
Name: one, dtype: object
-------------------------------------------
print(df2.loc[['one', 'three']])
[out]:
      char  int  float
one      a   10    1.1
three    c   30    3.3

使用.iloc()方法。

print(df2.iloc[0])
[out]:
char       a
int       10
float    1.1
Name: one, dtype: object
-------------------------------------------
print(df2.iloc[[0, 2]])
[out]:
      char  int  float
one      a   10    1.1
three    c   30    3.3

至此,关于Python Pandas中DataFrame索引及数据选取的介绍完毕。如需了解更多Python DataFrame索引相关内容,请查阅本站过往文章或继续浏览后续文章,感谢支持!

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

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 算法库。