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 package
import pandas as pd
 
# List of Tuples
students = [('Ankit', 22, 'A'),
           ('Swapnil', 22, 'B'),
           ('Priya', 22, 'B'),
           ('Shivangi', 22, 'B'),
            ]
# Create a DataFrame object
stu_df = pd.DataFrame(students, columns =['Name', 'Age', 'Section'],
                      index =['1', '2', '3', '4'])
 
stu_df
 

Output :
 

pandas-iterate

 

Method #2: Using [ ] operator : 
We can iterate over column names and select our desired column. 
Code : 
 

  • Python3
 
import pandas as pd
 
 
# List of Tuples
students = [('Ankit', 22, 'A'),
           ('Swapnil', 22, 'B'),
           ('Priya', 22, 'B'),
           ('Shivangi', 22, 'B'),
            ]
 
# Create a DataFrame object
stu_df = pd.DataFrame(students, columns =['Name', 'Age', 'Section'],
                      index =['1', '2', '3', '4'])
 
# Iterate over column names
for 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: 
 

iterate over columns in dataframe-2

posted @   Oops!#  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
历史上的今天:
2018-06-20 阿里云dataworks数据工场用户使用子账号
2018-06-20 NodeJS on Nginx: 使用nginx反向代理处理静态页面
点击右上角即可分享
微信分享提示