enumerate()、iterrows()

该函数在字面上是枚举、列举的意思,用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列, 同时列出数据和数据下标,一般用在 for 循环当中,可同时得到数据对象的值及对应的索引值#

In [152]:
   a=['ik','op','iu','ud']
for i in enumerate(a):
    print (i)
 
Out[152]
(0, 'ik')
(1, 'op')
(2, 'iu')
(3, 'ud')
In [153]:
for i,v in enumerate(a,2): #eneumerat(list,start=0) 其中的start参数是指从哪个序号开始。本例中是2,序号就是从2开始。
    print(i)
    print(v)
 Out[153]
2
ik
3
op
4
iu
5
ud
 

iterrows()

python里使用iterrows()对dataframe进行遍历

In [5]:
 import pandas as pd
 
In [6]:
b=pd.DataFrame({'a':[1,2,3,4,5],
               'b':['q','e','r','t','y']})
In [12]:
for i,row in b.iterrows():
    print(row)
    print(i)
Out[12]

a 1 b q Name: 0, dtype: object 0 a 2 b e Name: 1, dtype: object 1 a 3 b r Name: 2, dtype: object 2 a 4 b t Name: 3, dtype: object 3 a 5 b y Name: 4, dtype: object 4
In [14]:
for row in b.iterrows():
    print(row)
#如果只定义一个变量,那么row就是整个元组
(0, a    1
b    q
Name: 0, dtype: object)
(1, a    2
b    e
Name: 1, dtype: object)
(2, a    3
b    r
Name: 2, dtype: object)
(3, a    4
b    t
Name: 3, dtype: object)
(4, a    5
b    y
Name: 4, dtype: object)
原文地址:https://www.cnblogs.com/liyun1/p/11242056.html