Loop or Iterate over all or certain columns of a dataframe in Python-pandas 遍历pandas dataframe的所有列
In this article, we will discuss how to loop or Iterate overall or certain columns of a DataFrame? There are various methods to achieve this task.
Let’s first create a Dataframe and see that :
Code :
- Python3
# import pandas packageimport pandas as pd# List of Tuplesstudents = [('Ankit', 22, 'A'), ('Swapnil', 22, 'B'), ('Priya', 22, 'B'), ('Shivangi', 22, 'B'), ]# Create a DataFrame objectstu_df = pd.DataFrame(students, columns =['Name', 'Age', 'Section'], index =['1', '2', '3', '4'])stu_df |
Output :

Method #2: Using [ ] operator :
We can iterate over column names and select our desired column.
Code :
- Python3
import pandas as pd# List of Tuplesstudents = [('Ankit', 22, 'A'), ('Swapnil', 22, 'B'), ('Priya', 22, 'B'), ('Shivangi', 22, 'B'), ]# Create a DataFrame objectstu_df = pd.DataFrame(students, columns =['Name', 'Age', 'Section'], index =['1', '2', '3', '4'])# Iterate over column namesfor column in stu_df: # Select column contents by column # name using [] operator columnSeriesObj = stu_df[column] print('Column Name : ', column) print('Column Contents : ', columnSeriesObj.values) |
Output:


浙公网安备 33010602011771号