循环需要很多时间才能运行

时间:2019-10-16 19:52:59

标签: python pandas

有什么方法可以使下面的代码更有效。

for i in range(0, len(df)):
    current_row = df.iloc[i]    
    if i > 0:
        previous_row =df.iloc[i-1]
    else:
        previous_row = current_row 
    if (current_row['A'] != 1):
        if ((current_row['C'] < 55) and (current_row['D'] >= -1)):
            df.loc[i,'F'] = previous_row['F'] + 1
        else: 
            df.loc[i,'F'] = previous_row['F']

例如,如果数据框如下所示:

df = pd.DataFrame({'A':[1,1,1, 0, 0, 0, 1, 0, 0], 'C':[1,1,1, 0, 0, 0, 1, 1, 1], 'D':[1,1,1, 0, 0, 0, 1, 1, 1],
'F':[1,1,1, 0, 0, 0, 1, 1, 1]})

我的输出应该像这样

>>> df
   A  C  D  F
0  1  1  1  1
1  1  1  1  1
2  1  1  1  1
3  0  0  0  2
4  0  0  0  3
5  0  0  0  4
6  1  1  1  1
7  0  1  1  2
8  0  1  1  3

0 个答案:

没有答案