How To Iterate Over Rows Of A DataFrame?
Table Of Contents:
- Syntax For Iterating Over Rows Of Data Frame.
- Examples Of Rows Iteration.
(1) Syntax:
DataFrame.iterrows()
Description:
- Iterate over DataFrame rows as (index, Series) pairs.
Returns:
- index:label or tuple of label
The index of the row. A tuple for a MultiIndex.
data: Series The data of the row as a Series.
(2) Examples Of iterrows() Method:
Example-1
import pandas as pd
student = {'Name':['Subrat','Abhispa','Arpita','Anuradha','Namita'],
'Roll_No':[100,101,102,103,104],
'Subject':['Math','English','Science','History','Commerce'],
'Mark':[95,88,76,73,93]}
student_object = pd.DataFrame(student)
student_object
Output:
for label, content in student_object.iterrows():
print(f'Columns: {label}')
Output:
Columns: 0
Columns: 1
Columns: 2
Columns: 3
Columns: 4
Note:
- It has returned the column Indexes.
for label, content in student_object.iterrows():
print(f'content: {content}', sep='\n')
Output:
content:
Name Subrat
Roll_No 100
Subject Math
Mark 95
Gender Male
Name: 0, dtype: object
content:
Name Abhispa
Roll_No 101
Subject English
Mark 88
Gender Female
Name: 1, dtype: object
content:
Name Arpita
Roll_No 102
Subject Science
Mark 76
Gender Female
Name: 2, dtype: object
content:
Name Anuradha
Roll_No 103
Subject History
Mark 73
Gender Female
Name: 3, dtype: object
content:
Name Namita
Roll_No 104
Subject Commerce
Mark 93
Gender Female
Name: 4, dtype: object
Note:
- It has returned the Row Values.