Pandas >> How to Iterate Over Rows and Columns in a DataFrame in Pandas
Table of Contents
In this article, we will show you how to iterate all rows and columns of a DataFrame in Pandas
.
Firstly, we prepare a dataframe.
Preparing data
import pandas as pd
df = pd.DataFrame({
"name": ["Kevin", "Jack", "Mary", "Bob", "Robert", "Amy"],
"score": [80, 90, 95, 93, 88, 81],
"class": ["A", "B", "A", "A", "B", "B"]
}, index=["K", "J", "M", "B", "R", "A"])
df
Result
name | score | class | |
---|---|---|---|
K | Kevin | 80 | A |
J | Jack | 90 | B |
M | Mary | 95 | A |
B | Bob | 93 | A |
R | Robert | 88 | B |
A | Amy | 81 | B |
Use iterrows() of DataFrame to iterate over rows
We can use iterrows()
method of DataFrame
to iterate over all rows of DataFrame. iterrows()
method yields index
and Row Series
.
for index, row in df.iterrows():
print(f"{index}: {row['name']}")
Result
K: Kevin
J: Jack
M: Mary
B: Bob
R: Robert
A: Amy
Use iteritems() of Series to iterate over all values of Series
We can use iteritmes() method of Series to iterate over all values of Series. iteritems()
method will return iterable of tuples containing the (index, value) pairs from a Series.
for k, v in df.loc["K"].iteritems():
print(f"{k}: {v}")
Result
name: Kevin
score: 80
class: A
Use for … in Syntax to iterate over all columns
We can use for…in syntax to iterate over all columns of DataFrame. This will get every column name.
for col_name in df:
print(col_name)
# OR
for col_name in df.columns:
print(col_name)
Result
name
score
class
We can iterate over all columns by specifying each column name.
for col_name in df:
print(df[col_name])
Result
K Kevin
J Jack
M Mary
B Bob
R Robert
A Amy
Name: name, dtype: object
K 80
J 90
M 95
B 93
R 88
A 81
Name: score, dtype: int64
K A
J B
M A
B A
R B
A B
Name: class, dtype: object
Iterate all cells/values in a DataFrame
We can combine the iterations together to get each value of a DataFrame.
for index, row in df.iterrows():
print(f"{index}----------")
for col_name in df.columns:
print(f"{col_name}: {row[col_name]}")
K----------
name: Kevin
score: 80
class: A
J----------
name: Jack
score: 90
class: B
M----------
name: Mary
score: 95
class: A
B----------
name: Bob
score: 93
class: A
R----------
name: Robert
score: 88
class: B
A----------
name: Amy
score: 81
class: B