Looping Through DataFrame in Python

This tutorial will discuss how to loop through rows in a Pandas DataFrame.

How to Use Pandas to Cycle Through Rows in a Pandas DataFrame?

Python has a great environment of data-centric Python modules, which makes it a great tool for performing data analysis. One such tool, Pandas, greatly simplifies collecting and analyzing data.

Using the Index Attribute of the DataFrame

Code

Output:

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

Using loc[] Function of the DataFrame.

Code

Output:

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

Using iloc[] Method of the Pandas DataFrame

Code

Output:

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

Using iterrows() Method of the DataFrame

Code

Output:

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





Latest Courses