mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4mobile wallpaper 5mobile wallpaper 6mobile wallpaper 7mobile wallpaper 8mobile wallpaper 9mobile wallpaper 10mobile wallpaper 11mobile wallpaper 12mobile wallpaper 13mobile wallpaper 14mobile wallpaper 15mobile wallpaper 16mobile wallpaper 17mobile wallpaper 18mobile wallpaper 19mobile wallpaper 20mobile wallpaper 21mobile wallpaper 22mobile wallpaper 23
325 字
1 分钟
笔记|数据分析学习笔记19|DataFrame的访问

本系列所有文章都放在数据科学标签,总目录如下:

合集|数据分析学习笔记|系列总目录

上一篇:笔记|数据分析学习笔记18|DataFrame的属性


19.1 按行列访问(loc、iloc、at、iat)#

沿用前两节的 DataFrame:

import pandas as pd
import numpy as np
df = pd.DataFrame(
{
'name': ['tom', 'tom', 'jack', 'alice', 'bob', 'allen'],
'score': [60.5, 60.5, 80, 30.6, 70, 83.5],
'age': [15, 15, 15, 20, 26, 30]
},
index=[1, 2, 3, 4, 5, 6]
)

访问某行:

print(df.loc[4]) # 按标签取第4行
print(df.iloc[3]) # 按位置取第4行(索引从0开始)

输出:

name alice
score 30.6
age 20
Name: 4, dtype: object
name alice
score 30.6
age 20
Name: 4, dtype: object

访问某列:

print(df.loc[:, 'name']) # 所有行的 name 列
print(df.iloc[:, 0]) # 所有行的第1列

输出:

1 tom
2 tom
3 jack
4 alice
5 bob
6 allen
Name: name, dtype: object
1 tom
2 tom
3 jack
4 alice
5 bob
6 allen
Name: name, dtype: object

访问单个元素:

print(df.at[3, 'score']) # 标签访问
print(df.iat[2, 1]) # 位置访问(第3行第2列)
print(df.loc[3, 'score']) # loc 同样可访问单个元素
print(df.iloc[2, 1]) # iloc 同样可访问单个元素

输出:

80.0
80.0
80.0
80.0

19.2 获取单列与多列#

获取单列(返回 Series):

print(df['name'])
print(type(df['name'])) # <class 'pandas.core.series.Series'>
print(df.name) # 也可通过属性方式访问

输出:

1 tom
2 tom
3 jack
4 alice
5 bob
6 allen
Name: name, dtype: object
<class 'pandas.core.series.Series'>
1 tom
2 tom
3 jack
4 alice
5 bob
6 allen
Name: name, dtype: object

获取多列(返回 DataFrame):

print(df[['name', 'score']])
print(type(df[['name', 'score']])) # <class 'pandas.core.frame.DataFrame'>

输出:

name score
1 tom 60.5
2 tom 60.5
3 jack 80.0
4 alice 30.6
5 bob 70.0
6 allen 83.5
<class 'pandas.core.frame.DataFrame'>

要点: df['col'] 返回 Series,df[['col1', 'col2']](双层方括号)返回 DataFrame。


19.3 数据预览与筛选#

查看部分数据:

print(df.head(2)) # 前2行
print(df.tail(3)) # 后3行

输出:

name score age
1 tom 60.5 15
2 tom 60.5 15
name score age
4 alice 30.6 20
5 bob 70.0 26
6 allen 83.5 30

布尔索引筛选:

print(df[df.score > 70]) # 单条件
print(df[(df.score > 70) & (df.age < 20)]) # 多条件(与)

输出:

name score age
3 jack 80.0 15
6 allen 83.5 30
name score age
3 jack 80.0 15

随机抽样:

print(df.sample(3)) # 随机抽取3行

输出(结果随机):

name score age
6 allen 83.5 30
1 tom 60.5 15
4 alice 30.6 20

19.4 本节小结#

本节完成了以下内容:

  • 掌握了 loc(按标签)、iloc(按位置)、atiat 四种索引器的用法。
  • 理解了单列(df['col'] 返回 Series)与多列(df[['c1', 'c2']] 返回 DataFrame)的区别。
  • 学会了 head()tail() 预览、布尔索引多条件筛选(& / |)、sample() 随机抽样。

下一节我们将学习 DataFrame 的常用方法

下一篇:笔记|数据分析学习笔记20|DataFrame的常用方法


分享

如果这篇文章对你有帮助,欢迎分享给更多人!

笔记|数据分析学习笔记19|DataFrame的访问
https://luq-blog.xyz/posts/2026-07-04-data-notes-19-df-access/
作者
Luquiescene
发布于
2026-07-04
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

目录