首页 > 解决方案 > 有没有一种体面的方法来计算数据框中的迭代值?

问题描述

我有两个数据框看起来像:

   col1  
0  1     

   col2  
0  2
1  3
2  4
3  5
4  6  

我的目标是使用 col2 中的数字填充 col1:

   col1      col2
0  1          2
1  2(=1x2)    3   
2  6(=2x3)    4
3  24(=6x4)   5
4  102(=24x5) 6 

因此,col1 中的数字计算为上一行 col1 中的值与上一行 col2 中的值的乘积。

标签: pythonpandas

解决方案


如果性能很重要,我认为numba是在这里使用循环的方式:

@jit(nopython=True)
def func(a, b):
    res = np.empty(a.shape)
    res[0] = b
    for i in range(1, a.shape[0]):
        res[i] = res[i-1] * a[i-1]
    return res

df2['col1'] = func(df2['col2'].values, df1.loc[0, 'col1'])

print (df2)
   col2   col1
0     2    1.0
1     3    2.0
2     4    6.0
3     5   24.0
4     6  120.0

推荐阅读