Python Pandas DataFrame 常用操作指南

顾星河
顾星河
发布时间:2026-10-12| 4人浏览过
原创

本文详细介绍 Python Pandas 库中 DataFrame 的核心操作方法。涵盖基础属性获取(如 index、shape)、数据访问(loc、iloc)、多行多列切片、条件筛选、列的新增与删除,以及数据修改。通过具体代码示例,帮助开发者快速掌握 DataFrame 的高效数据处理技巧。

获取 DataFrame 基础属性

在开始处理数据前,了解 DataFrame 的基本结构至关重要。Pandas 提供了多个属性来快速获取数据概览:

  • index:获取行索引。
  • values:获取 DataFrame 中的元素值(返回 NumPy 数组)。
  • columns:获取列名。
  • dtypes:获取每列的数据类型。
  • size:获取元素的总个数(行数 × 列数)。
  • ndim:获取维度数(DataFrame 通常为 2)。
  • shape:获取形状大小(返回元组:行数, 列数)。
  • T:对 DataFrame 进行转置操作。

以下代码展示了如何读取 Excel 数据并获取上述属性:

import pandas as pd
# 读取 Excel 数据
detail = pd.read_excel('E:\data\meal_order_detail.xlsx')

# 获取各项基础属性
print("索引", detail.index)
print("所有值:", detail.values)
print("所有列名:", detail.columns)
print("数据类型:", detail.dtypes)
print("元素个数:", detail.size)
print("维度:", detail.ndim)
print("形状大小(尺寸):", detail.shape)

# 使用 T 属性进行转置
print("转置前的形状:", detail.shape)
print("转置后的形状:", detail.T.shape)

数据访问与切片操作

Pandas 提供了多种访问数据的方式,包括字典式访问、属性访问以及基于标签和位置的切片方法。

1. 字典式与属性访问

可以通过方括号 [] 直接访问列,或者使用点号 . 访问属性(注意:列名不能包含空格或特殊字符,且不能与 DataFrame 方法冲突)。

# 使用字典访问方式获取单列
order_id = detail['order_id']
print("订单详情表的 order_id 的形状:", order_id.shape)

# 使用访问属性的方式获取单列
dishes_name = detail.dishes_name
print("订单详情表中的 dishes_name 的形状:", dishes_name.shape)

# 获取单列的前几行
dishes_name5 = detail['dishes_name'][:5]
print(dishes_name5)

# 获取多列多行数据(注意:多列需用双层方括号 [[...]])
orderDish = detail[['order_id', 'dishes_name']][:5]
print(orderDish)

# 访问多行数据(切片)
order5 = detail[:][1:6]
print("订单详情表中的 1~6 行元素的数据:\n", order5)

2. head() 与 tail() 方法

快速获取前几行或后几行数据,默认返回前 5 行或后 5 行,可通过参数指定数量。

# 获取前 5 行数据
print('订单详情表中前 5 行数据:\n', detail.head())

# 获取后 5 行数据
print('订单详情表中后 5 行数据:\n', detail.tail())

3. loc 与 iloc 方法详解

loc 基于标签(Label)进行访问,iloc 基于整数位置(Integer Location)进行访问。

  • loc[行索引名称或条件, 列索引名称]
  • iloc[行索引位置, 列索引位置]

单列/单元素访问:

# 使用 loc 提取指定列(按列名)
dishes_name1 = detail.loc[:, 'dishes_name']
print("使用 loc 提取 dishes_name 列的 size:", dishes_name1.size)

# 使用 iloc 提取指定列(按位置,从 0 开始)
dishes_name2 = detail.iloc[:, 3]
print("使用 iloc 提取第 3 列的 size:", dishes_name2.size)

多列与花式切片:

# 使用 loc、iloc 实现多列切片
orderDish1 = detail.loc[:, ['order_id', 'dishes_name']]
print(orderDish1.size)

orderDish2 = detail.iloc[:, [1, 3]]
print(orderDish2.size)

# 使用 loc、iloc 实现花式切片(指定具体行和列)
# 获取行名为 3,列名为 order_id 和 dishes_name 的数据
print("列名为 order_id 和 dishes_name 的行名为 3 的数据:\n", detail.loc[3, ['order_id', 'dishes_name']])

# 获取行名 2~6,列名为 order_id 和 dishes_name 的数据
print('列名为 order_id 和 dishes_name 行名为 2、3、4、5、6 的数据为:\n', detail.loc[2:6, ['order_id', 'dishes_name']])

# 获取行位置为 3,列位置为 1 和 3 的数据
# 注意:loc 传入的是索引名称或条件,iloc 传入的是位置
print('列名 1 和 3,行位置为 3 的数据为:\n', detail.iloc[3, [1, 3]])

# 获取行位置 2~6(注意:iloc 切片右边界不包含,即 2:7 取到 6),列位置 1 和 3 的数据
print('列位置为 1 和 3,行位置为 2,3,4,5,6 的数据和:\n', detail.iloc[2:7, [1, 3]])

条件切片:

# 使用 loc 实现条件切片:获取 order_id 为 458 的 dishes_name
print('detail 中 order_id 为 458 的 dishes_name 为:\n', detail.loc[detail['order_id'] == 458, ['order_id', 'dishes_name']])

# 使用 iloc 实现条件切片:获取 order_id 为 458 的第 1、5 列数据
# 注意:iloc 需要布尔数组,因此使用 .values 将条件转换为 NumPy 数组
print("detail 中 order_id 为 458 的第 1、5 列的数据为:\n", detail.iloc[(detail['order_id'] == 458).values, [1, 5]])

4. ix 方法(已弃用)

ix 方法允许同时使用标签和位置,但在较新版本的 Pandas 中已被弃用,建议统一使用 loc(标签)或 iloc(位置)。

# 比较 loc、iloc 和 ix 的切片结果(仅供参考,不推荐在生产环境使用 ix)
print('列名为 dishes_name 行名为 2,3,4,5,6 的数据为:\n', detail.loc[2:6, ['dishes_name']])
print('列位置为 5 行名为 2~6 的数据为:\n', detail.iloc[2:6, 5])
print('列位置为 5 行名为 2~6 的数据为:\n', detail.ix[2:6, 5])

数据修改与列操作

1. 修改数据

可以使用 loc 或 iloc 结合条件来修改特定单元格的值。

# 将 order_id 为 458 的记录修改为 45800
# 注意:45800 是整数,不需要单引号
detail.loc[detail['order_id'] == 458, 'order_id'] = 45800

print('更改后 detail 中的 order_id 为 458 的:\n', detail.loc[detail['order_id'] == 458, 'order_id'])
print('更改后 detail 中的 order_id 为 45800 的:\n', detail.loc[detail['order_id'] == 45800, 'order_id'])

# 恢复原值
detail.loc[detail['order_id'] == 45800, 'order_id'] = 458

2. 新增列

可以通过直接赋值的方式新增列,支持定值和非定值(基于其他列计算)。

# 新增一列非定值:计算支付金额(数量 * 单价)
detail['payment'] = detail['counts'] * detail['amounts']
print('detail 新增列 payment 的前 5 行数据为:\n', detail['payment'].head())

# 新增一列定值:统一支付方式为“现金支付”
detail['pay_way'] = '现金支付'
print('detail 新增列的前 5 行的数据为:\n', detail['pay_way'].head())

3. 删除数据(drop)

使用 drop 方法可以删除指定的行或列。注意设置 inplace=True 以直接修改原 DataFrame,否则返回一个新的 DataFrame。

# 删除某列:删除 pay_way 列
print('删除 pay_way 前 detail 中的列索引为:\n', detail.columns)
detail.drop(labels='pay_way', axis=1, inplace=True)
print('删除 pay_way 后 detail 中的列索引为:\n', detail.columns)

# 删除某几行:删除第 1 到 10 行(注意:range(1,11) 不包含 11)
print('删除 1~10 行前 detail 的长度:', len(detail))
detail.drop(labels=range(1, 11), axis=0, inplace=True)
print('删除 1~10 行后 detail 的长度:', len(detail))

以上就是 Python Pandas DataFrame 常用操作的详细内容,更多关于 Python 数据处理技巧的资料请关注本站其它相关文章!

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

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