Python Pandas — II — Question 2
Back to all questionsWrite a program to print a DataFrame one row at a time and print only first five rows.
import pandas as pd
data = {
'Name': ['Amruta', 'Harsh', 'Yogesh', 'Shreya', 'Zoya', 'Nyra'],
'Age': [25, 30, 35, 40, 45, 28],
'City': ['Chandigarh', 'Jaipur', 'Dehradun', 'Delhi', 'Vadodara', 'Guwahati']
}
df = pd.DataFrame(data)
first_five_rows = df.head(5)
print("Each row:")
for index, row in first_five_rows.iterrows():
print("Index:", index)
print(row)Each row:
Index: 0
Name Amruta
Age 25
City Chandigarh
Name: 0, dtype: object
Index: 1
Name Harsh
Age 30
City Jaipur
Name: 1, dtype: object
Index: 2
Name Yogesh
Age 35
City Dehradun
Name: 2, dtype: object
Index: 3
Name Shreya
Age 40
City Delhi
Name: 3, dtype: object
Index: 4
Name Zoya
Age 45
City Vadodara
Name: 4, dtype: object
import
pandas
as
pd
data
=
{
'Name'
: [
'Amruta'
,
'Harsh'
,
'Yogesh'
,
'Shreya'
,
'Zoya'
,
'Nyra'
],
'Age'
: [
25
,
30
,
35
,
40
,
45
,
28
],
'City'
: [
'Chandigarh'
,
'Jaipur'
,
'Dehradun'
,
'Delhi'
,
'Vadodara'
,
'Guwahati'
]
}
df
=
pd
.
DataFrame
(
data
)
first_five_rows
=
df
.
head
(
5
)
print
(
"Each row:"
)
for
index
,
row
in
first_five_rows
.
iterrows
():
print
(
"Index:"
,
index
)
print
(
row
)
Output
Each row:
Index: 0
Name Amruta
Age 25
City Chandigarh
Name: 0, dtype: object
Index: 1
Name Harsh
Age 30
City Jaipur
Name: 1, dtype: object
Index: 2
Name Yogesh
Age 35
City Dehradun
Name: 2, dtype: object
Index: 3
Name Shreya
Age 40
City Delhi
Name: 3, dtype: object
Index: 4
Name Zoya
Age 45
City Vadodara
Name: 4, dtype: object