pandas中loc和iloc的区别

在 Pandas 中,lociloc 是用于选择和过滤数据的两种主要方法,它们的区别在于使用的索引类型。

1. loc:基于标签索引

  • loc 是基于行或列的标签(label)来选择数据。它可以按行或列的名称来访问数据,也可以通过布尔索引选择。
  • 支持的索引类型:行标签、列标签、布尔索引。
  • 语法DataFrame.loc[row_indexer, column_indexer]

示例

python 复制代码
import pandas as pd

# 创建示例数据
df = pd.DataFrame({
    'A': [1, 2, 3, 4],
    'B': [5, 6, 7, 8],
    'C': [9, 10, 11, 12]
}, index=['a', 'b', 'c', 'd'])

# 使用 loc 基于行标签选择
print(df.loc['a'])  # 选择标签为 'a' 的行

输出

复制代码
A    1
B    5
C    9
Name: a, dtype: int64
loc 示例用法:
  • 选择行和列:使用行和列标签选择特定的元素或切片。
python 复制代码
df.loc['b', 'A']  # 选择标签为 'b' 的行,'A' 列的元素
  • 选择多个行或列
python 复制代码
df.loc[['a', 'b'], ['A', 'B']]  # 选择 'a' 和 'b' 行的 'A' 和 'B' 列
  • 布尔索引
python 复制代码
df.loc[df['A'] > 2]  # 选择 'A' 列中大于 2 的行

2. iloc:基于整数位置索引

  • iloc 是基于行或列的整数位置(即位置编号)来选择数据。它的工作方式类似于 NumPy 的数组索引方式。
  • 支持的索引类型:整数位置。
  • 语法DataFrame.iloc[row_indexer, column_indexer]

示例

python 复制代码
# 使用 iloc 基于位置选择
print(df.iloc[0])  # 选择位置为 0 的行

输出

复制代码
A    1
B    5
C    9
Name: a, dtype: int64
iloc 示例用法:
  • 选择单个元素
python 复制代码
df.iloc[1, 0]  # 选择位置为 (1, 0) 的元素
  • 选择多个行或列
python 复制代码
df.iloc[0:2, 0:2]  # 选择前两行和前两列

区别总结

特性 loc(基于标签) iloc(基于位置)
索引类型 行/列的标签(可以是字符串、日期等) 行/列的整数位置
支持的索引 标签索引、布尔索引 整数位置索引
示例 df.loc['a'] df.iloc[0]
切片 标签的范围包含最后一个索引(闭区间) 索引的范围不包含最后一个位置(开区间)

具体场景:

  • loc 更适合当你知道数据的标签(比如行名、列名)时,可以进行精确或基于条件的访问。
  • iloc 更适合当你按数据的具体位置(比如第几行、第几列)进行访问时。
相关推荐
智航GIS4 小时前
11.6 Pandas数据处理进阶:缺失值处理与数据类型转换完全指南
python·pandas
西红市杰出青年10 小时前
crawl4ai------AsyncPlaywrightCrawlerStrategy使用教程
开发语言·python·架构·正则表达式·pandas
CCPC不拿奖不改名1 天前
数据处理与分析:pandas基础+面试习题
开发语言·数据结构·python·面试·职场和发展·pandas
4***17541 天前
Python酷库之旅-第三方库Pandas(051)
开发语言·python·pandas
万粉变现经纪人2 天前
如何解决 pip install mysqlclient 报错 ‘mysql_config’ not found 问题
数据库·python·mysql·pycharm·bug·pandas·pip
智航GIS2 天前
11.3 Pandas 模块功能概览
python·信息可视化·pandas
White-Camellia3 天前
Pandas多个数据表合并(merge)
pandas
muddjsv3 天前
Pandas 绘图全能手册:12 类基础图一键绘制,覆盖所有原生绘图类型
pandas
程序猿零零漆3 天前
Spring之旅 - 记录学习 Spring 框架的过程和经验(十四)SpringMVC的请求处理
学习·spring·pandas
weixin_462446233 天前
Python 使用 PyQt5 + Pandas 实现 Excel(xlsx)批量合并工具(带图形界面)
python·qt·pandas