python for循环更新值

时间:2015-06-22 20:16:49

标签: python numpy pandas

我有一个超过10k行的pandas数据帧。我需要迭代每一行,并根据更新后的前一行的值进行数学运算。因为循环非常慢。

示例DF:

a  b  c
1  2  3
2  3  4
3  4  5

for循环示例:

for i in range(1,len(DF)):
  DF['b'] = DF['b'].[i-1]+DF['c']

我也试过

DF['b'] = DF['b'].shift(1)+DF['c']

但不会使用更新后的值' b'。

进行此类计算的最佳方法是什么?

ANSWERED: loc和iloc有帮助。 最好的方法是:

for i in range(1, len(DF)):
  DF.loc[i, 'b'] = DF.loc[i-1, 'b'] + DF.loc[i, 'c']

1 个答案:

答案 0 :(得分:1)

使用iloc

for i in range(1,len(DF)):
    DF.iloc[i]['b'] = DF.iloc[i-1]['b']+DF.iloc['i']['c']