CBSE Class 12 Informatics Practices
Question 14 of 44
Data Handling using Pandas — Question 15
Back to all questions 15
Question Write a program to iterate and print a dataframe column-wise and print only first three columns.
import pandas as pd
data = {
'Name': ['Aliya', 'Hemanth', 'Charlie'],
'Age': [25, 30, 35],
'City': ['Bangalore', 'Chennai', 'Mumbai'],
'Salary': [50000, 60000, 70000]
}
df = pd.DataFrame(data)
first_three_columns = df.iloc[:, :3]
print("Each column:")
for column_name in first_three_columns:
column_data = first_three_columns[column_name]
print(column_name)
print(column_data)Each column:
Name
0 Aliya
1 Hemanth
2 Charlie
Name: Name, dtype: object
Age
0 25
1 30
2 35
Name: Age, dtype: int64
City
0 Bangalore
1 Chennai
2 Mumbai
Name: City, dtype: object
import
pandas
as
pd
data
=
{
'Name'
: [
'Aliya'
,
'Hemanth'
,
'Charlie'
],
'Age'
: [
25
,
30
,
35
],
'City'
: [
'Bangalore'
,
'Chennai'
,
'Mumbai'
],
'Salary'
: [
50000
,
60000
,
70000
]
}
df
=
pd
.
DataFrame
(
data
)
first_three_columns
=
df
.
iloc
[:, :
3
]
print
(
"Each column:"
)
for
column_name
in
first_three_columns
:
column_data
=
first_three_columns
[
column_name
]
print
(
column_name
)
print
(
column_data
)
Output
Each column:
Name
0 Aliya
1 Hemanth
2 Charlie
Name: Name, dtype: object
Age
0 25
1 30
2 35
Name: Age, dtype: int64
City
0 Bangalore
1 Chennai
2 Mumbai
Name: City, dtype: object