Python Pandas DataFrame行列选择与切片操作详解

认真发呆
认真发呆
发布时间:2026-10-13| 5人浏览过
原创

本文详解Python Pandas中DataFrame的行列选择与切片方法。对比loc、iloc、at、iat及ix函数的用法,说明基于标签与位置索引的区别。通过实例展示正确与错误的代码写法,总结各方法的适用场景及常见错误,帮助开发者高效进行数据筛选。

在SQL中,select语句依据列名进行选取;而Pandas提供了更灵活的选择方式,不仅支持按列名选取,还支持按列的位置(即数字索引,注意Pandas中行列索引从0开始)进行选取。相关函数包括以下几种:

1)loc:基于列的标签(label),可选择特定的行(通过行索引index);

2)iloc:基于行或列的位置(position);

3)at:根据指定的行索引index及列标签label,快速定位DataFrame中的元素;

4)iat:与at类似,但根据位置(position)进行定位;

5)ix:作为loc与iloc的混合体,既支持标签也支持位置索引;

实例

import pandas as pd
import numpy as np


df = pd.DataFrame({'total_bill': [16.99, 10.34, 23.68, 23.68, 24.59],
          'tip': [1.01, 1.66, 3.50, 3.31, 3.61],
          'sex': ['Female', 'Male', 'Male', 'Male', 'Female']})
# data type of columns
print df.dtypes
# indexes
print df.index
# return pandas.Index
print df.columns
# each row, return array[array]
print df.values
print df
sex      object
tip      float64
total_bill  float64
dtype: object
RangeIndex(start=0, stop=5, step=1)
Index([u'sex', u'tip', u'total_bill'], dtype='object')
[['Female' 1.01 16.99]
 ['Male' 1.66 10.34]
 ['Male' 3.5 23.68]
 ['Male' 3.31 23.68]
 ['Female' 3.61 24.59]]
   sex  tip total_bill
0 Female 1.01    16.99
1  Male 1.66    10.34
2  Male 3.50    23.68
3  Male 3.31    23.68
4 Female 3.61    24.59
print df.loc[1:3, ['total_bill', 'tip']]
print df.loc[1:3, 'tip': 'total_bill']
print df.iloc[1:3, [1, 2]]
print df.iloc[1:3, 1: 3]
  total_bill  tip
1    10.34 1.66
2    23.68 3.50
3    23.68 3.31
  tip total_bill
1 1.66    10.34
2 3.50    23.68
3 3.31    23.68
  tip total_bill
1 1.66    10.34
2 3.50    23.68
  tip total_bill
1 1.66    10.34
2 3.50    23.68

错误的表示:

print df.loc[1:3, [2, 3]]#.loc仅支持列名操作
KeyError: 'None of [[2, 3]] are in the [columns]'
print df.loc[[2, 3]]#.loc可以不加列名,则是行选择
  sex  tip total_bill
2 Male 3.50    23.68
3 Male 3.31    23.68
print df.iloc[1:3]#.iloc可以不加第几列,则是行选择
sex  tip total_bill
1 Male 1.66    10.34
2 Male 3.50    23.68
print df.iloc[1:3, 'tip': 'total_bill']
TypeError: cannot do slice indexing on <class 'pandas.indexes.base.Index'> with these indexers [tip] of <type 'str'>

print df.at[3, 'tip']
print df.iat[3, 1]
print df.ix[1:3, [1, 2]]
print df.ix[1:3, ['total_bill', 'tip']]
3.31
3.31
  tip total_bill
1 1.66    10.34
2 3.50    23.68
3 3.31    23.68
  total_bill  tip
1    10.34 1.66
2    23.68 3.50
3    23.68 3.31
print df.ix[[1, 2]]#行选择
  sex  tip total_bill
1 Male 1.66    10.34
2 Male 3.50    23.68
print df[1: 3]
print df[['total_bill', 'tip']]
# print df[1:2, ['total_bill', 'tip']] # TypeError: unhashable type
sex  tip total_bill
1 Male 1.66    10.34
2 Male 3.50    23.68
  total_bill  tip
0    16.99 1.01
1    10.34 1.66
2    23.68 3.50
3    23.68 3.31
4    24.59 3.61
print df[1:3,1:2]
TypeError: unhashable type

总结

1).loc、.iloc、.ix,若只添加第一个参数如.loc([1,2])、.iloc([2:3])、.ix[2]等,则执行的是行选择;

2).loc、.at,选择列时只能使用列名,不能使用位置索引;

3).iloc、.iat,选择列时只能使用位置索引,不能使用列名;

4)df[]只能进行行选择或列选择,不能同时进行行列选择,且列选择只能使用列名。

以上这篇关于Python Pandas 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 算法库。