Iterate over a DataFrame with iterrows() and items()
Expt. No.13
Page No.26
iterrows() and items()
Aim
To write a Python program that goes through a DataFrame row by row with iterrows() and column by column with items().
Concepts used
Algorithm
- Create a DataFrame of names and marks.
- Loop with iterrows(): each step gives the row label and the row as a Series.
- Loop with items(): each step gives the column name and the column as a Series.
Program
# Iterating over a DataFrame import pandas as pd df = pd.DataFrame({"Name": ["Asha", "Rohan", "Ira"], "Marks": [82, 67, 88]}, index=["S1", "S2", "S3"]) print("Row by row with iterrows():")for label, row in df.iterrows(): print(label, row["Name"], row["Marks"]) print("Column by column with items():")for col, values in df.items(): print("Column:", col) print(values.values)
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python dataframe_iteration.py
Row by row with iterrows():
S1 Asha 82
S2 Rohan 67
S3 Ira 88
Column by column with items():
Column: Name
['Asha' 'Rohan' 'Ira']
Column: Marks
[82 67 88]
✓ Printed by running this program, not typed by hand.
Result
iterrows() gave each row label with the row's values (S1 Asha 82, …). items() gave each column name with its values as an array.
Viva voce: what the examiner may ask
01What does iterrows() return at each step?
A pair: the row label and the row as a Series.
02What does items() return at each step?
A pair: the column name and the column as a Series.
03What happened to iteritems()?
It was removed in Pandas 2.0; items() does the same job.
Variations for the lab test
- Print only the names of students who scored above 80 using iterrows().
- Print the total marks of all students using a loop.
- Print each column's name with its first value.
! Common mistake Using
iteritems() in Pandas 2.x raises AttributeError; use items().