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 :
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:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
2018-06-20 阿里云dataworks数据工场用户使用子账号
2018-06-20 NodeJS on Nginx: 使用nginx反向代理处理静态页面