DataFrame.iterrows函数

DataFrame.iterrows函数 首页 / Pandas入门教程 / DataFrame.iterrows函数

如果要遍历DataFrame以对每行执行一些操作,则可以在Pandas中使用iterrows()函数。Pandas使用三个函数来迭代DataFrame的行,即iterrows(),iteritems()和itertuples()。

迭代行:

iterrows()负责遍历DataFrame的每一行。它返回一个迭代器,该迭代器包含作为Series的每一行的索引和数据。

此函数返回每个索引值以及包含每一行数据的序列。

无涯教程网

  • iterrows()       -  用于将行作为(index,Series)对进行迭代。
  • iteritems()      -  用于迭代(key,value)对。
  • itertuples()     -  用于将行作为命名元组进行迭代。

Yields:

  • index   -  返回行的索引和MultiIndex的元组。
  • data     - 以行的形式返回该行的数据。
  • it           - 返回在框架的行上进行迭代的生成器。

例1

import pandas as pd
import numpy as np

info = pd.DataFrame(np.random.randn(4,2),columns = ['col1','col2'])
for row_index,row in info.iterrows():
   print (row_index,row)

输出

0   name        John
     degree      B.Tech
score         90
Name: 0, dtype: object

1 name      Learnfk
degree    B.Com
score        40
Name: 1, dtype: object

2 name      Alexander
degree        M.Com
score            80
Name: 2, dtype: object

3 name      William
degree     M.Tech
score          98
Name: 3, dtype: object

例2

# importing pandas module  
import pandas as pd  
     
# 从csv文件制作数据框
data = pd.read_csv("aa.csv")  
  
for i, j in data.iterrows(): 
    print(i, j) 
    print()

输出

0           Name                  Hire Date     Salary            Leaves Remaining    0   John Idle                  03/15/14     50...
Name: 0, dtype: object

1           Name                  Hire Date     Salary            Leaves Remaining    1     Learnfk Gilliam        06/01/15      65000...
Name: 1, dtype: object

2           Name                  Hire Date     Salary            Leaves Remaining    2     Parker Chapman   05/12/14      45000.0   ...
Name: 2, dtype: object

3           Name                  Hire Date     Salary            Leaves Remaining    3     Jones Palin             11/01/13     700...
Name: 3, dtype: object

4           Name                  Hire Date     Salary            Leaves Remaining    4     Terry Gilliam          08/12/14     4800...
Name: 4, dtype: object

5           Name                  Hire Date     Salary            Leaves Remaining    5     Michael Palin         05/23/13     66000...
Name: 5, dtype: object

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

赵成的运维体系管理课 -〔赵成〕

数据结构与算法之美 -〔王争〕

网络编程实战 -〔盛延敏〕

高并发系统设计40问 -〔唐扬〕

性能工程高手课 -〔庄振运〕

容量保障核心技术与实战 -〔吴骏龙〕

业务开发算法50讲 -〔黄清昊〕

Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕

结构思考力 · 透过结构看思考 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)