How To Iterate Over Columns Of A DataFrame?
Table Of Contents:
- Syntax For Iterating Over Columns Of Data Frame.
- Examples Of Column Iteration.
(1) Syntax:
DataFrame.items()
Description:
Iterate over (column name, Series) pairs.
Iterates over the DataFrame columns, returning a tuple with the column name and the content as a Series.
Returns:
label: object- The column names for the DataFrame being iterated over.
content: Series – The column entries belonging to each label, as a Series.
(2) Examples Of items() 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.items():
print(f'Columns: {label}')
Output:
Columns: Name
Columns: Roll_No
Columns: Subject
Columns: Mark
Columns: Gender
Note:
- It has returned the column names.
for label, content in student_object.items():
print(f'content: {content}', sep='\n')
Output:
content:
0 Subrat
1 Abhispa
2 Arpita
3 Anuradha
4 Namita
Name: Name, dtype: object
content:
0 100
1 101
2 102
3 103
4 104
Name: Roll_No, dtype: int64
content:
0 Math
1 English
2 Science
3 History
4 Commerce
Name: Subject, dtype: object
content:
0 95
1 88
2 76
3 73
4 93
Name: Mark, dtype: int64
content:
0 Male
1 Female
2 Female
3 Female
4 Female
Name: Gender, dtype: object
Note:
- It has returned, column values as a Series.