在 Python 中遍历 DataFrame

2024 年 8 月 29 日 | 阅读 3 分钟

本教程将讨论如何遍历 Pandas DataFrame 中的行。

如何使用 Pandas 循环遍历 Pandas DataFrame 的行?

Python 拥有强大的数据相关 Python 模块环境,使其成为执行数据分析的绝佳工具。其中一个工具 Pandas,大大简化了数据的收集和分析。

使用 DataFrame 的 Index 属性

代码

输出

Given DataFrame:
    1   2   3
0  a  a1  a2
1  b  b1  b2
2  c  c1  c2
3  d  d1  d2
4  e  e1  e2

Iterating over the rows using the index attribute:

a a1
b b1
c c1
d d1
e e1

使用 DataFrame 的 loc[] 函数。

代码

输出

Given DataFrame:
    1   2   3
0  a  a1  a2
1  b  b1  b2
2  c  c1  c2
3  d  d1  d2
4  e  e1  e2

Iterating over the rows using the index attribute:

a a1
b b1
c c1
d d1
e e1

使用 Pandas DataFrame 的 iloc[] 方法

代码

输出

Given DataFrame:
    1   2   3
0  a  a1  a2
1  b  b1  b2
2  c  c1  c2
3  d  d1  d2
4  e  e1  e2

Iterating over the rows using the index attribute:

a a2
b b2
c c2
d d2
e e2

使用 DataFrame 的 iterrows() 方法

代码

输出

Given DataFrame:
    1   2   3
0  a  a1  a2
1  b  b1  b2
2  c  c1  c2
3  d  d1  d2
4  e  e1  e2

Iterating over the rows using the iterrows() method:

a a1
b b1
c c1
d d1
e e1