Looping Over Dataframe
Tags: #pandas #python #loops #dataframes #forloop #loop #snippet
This notebook will help you in looping over your tables and getting concise information

Input

Import Library

1
import pandas as pd
2
import numpy as np
Copied!

Model

Loopring over dataframes can be a a lifesaver when there are lots of columns and we want to view our data at a go. This is an advntage of for loop in a dataframe.

Create Sample Dataframe

1
dict1 = {
2
"student_id": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
3
"student_name": ["Peter", "Dolly", "Maggie", "David", "Isabelle", "Harry", "Akin", "Abbey", "Victoria", "Sam"],
4
"student_course": np.random.choice(["Biology", "Physics", "Chemistry"], size=10)
5
}
Copied!
1
data = pd.DataFrame(dict1)
Copied!
1
data
Copied!

Output

Looping over the data to get the column name

1
for column in data:
2
print(column)
Copied!

Looping over the data to view the columns and their values sequentially

1
for k, v in data.iteritems():
2
print(k)
3
print(v)
Copied!

Looping over dataframes to get the informtion about a row with respect to its columns

1
for k, v in data.iterrows():
2
print(k)
3
print(v)
Copied!

Looping over datafrmes to view the data per row as a tuple with the column values

1
for row in data.itertuples():
2
print(row)
Copied!
Copy link
Edit on GitHub