迭代行,并控制计数i ++

时间:2015-10-23 10:17:21

标签: python loops pandas dataframe

我正在寻找迭代行的方法,但仅对每个第20或第30行值应用某种方法 所以像:

更新代码

for index, row in df.iterrows(), index=+20:
     location= geolocator.reverse("%s, %s" % (row['lat'],row['long']),timeout=None)
      row['location']=location.address
      time.sleep(3)
return df

实际上我尝试最小化请求的数量,否则我有超时问题。这就是为什么我尝试迭代行,并且仅对每个第20或第60行应用请求函数(因为我有7000行)而不是通过应用time.sleep方法来加速该过程

3 个答案:

答案 0 :(得分:4)

试试这个:

for index, row in enumerate(df):
    if index % 20 == 0:
        # do something

答案 1 :(得分:2)

只需使用enumerate和模数运算符:

for index, row in enumerate(df.iterrows()):
    if not index%20:
        row['C']=some_function()
return df

我将return从循环中取出,以便循环在一次迭代后不会结束。

答案 2 :(得分:0)

为什么不使用iloc和步骤参数来分割df:

示例:

In [120]:
df = pd.DataFrame({'c':np.random.randn(30)})
df

Out[120]:
           c
0  -0.737805
1   1.158012
2  -0.348384
3   0.044989
4   0.962584
5   2.041479
6   1.376785
7   0.208565
8  -1.535244
9   0.389831
10  0.049862
11 -0.142717
12 -0.794087
13  1.316492
14  0.182952
15  0.850953
16  0.015589
17  0.062692
18 -1.551303
19  0.937899
20  0.583003
21 -0.612411
22  0.762307
23 -0.682298
24 -0.897314
25 -0.101144
26 -0.617573
27 -2.168498
28  0.631021
29 -1.592888

In [121]:
df['c'].iloc[::5] = 0
df

Out[121]:
           c
0   0.000000
1   1.158012
2  -0.348384
3   0.044989
4   0.962584
5   0.000000
6   1.376785
7   0.208565
8  -1.535244
9   0.389831
10  0.000000
11 -0.142717
12 -0.794087
13  1.316492
14  0.182952
15  0.000000
16  0.015589
17  0.062692
18 -1.551303
19  0.937899
20  0.000000
21 -0.612411
22  0.762307
23 -0.682298
24 -0.897314
25  0.000000
26 -0.617573
27 -2.168498
28  0.631021
29 -1.592888

这比迭代每一行要快得多

所以在你的情况下:

df['C'].iloc[::20] = some_function()

应该有效