python-如何在python数据帧中执行以下操作

时间:2020-11-08 11:12:13

标签: python pandas dataframe

以下是我的df

df = pd.DataFrame({
                   'Sr. No': [1, 2, 3, 4, 5, 6],
                    'val1' : [2,3,2,4,1,2],

})

我想要输出val2,如下图所示。 row1与val1的row1相同,但row2及以下的内容是使用公式计算得出的,

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

因此,所有行都依赖于前一行,例如C4取决于C3的计算。因此,我们可以直接在numpy数组上进行操作。

sr_no_vals = df['Sr. No'].values
val1_vals = df['val1'].values
val2_vals = [val1_vals[0]]

for i in range(1, len(sr_no_vals)):
    calculated_value = (((1 + val2_vals[i - 1]) ** sr_no_vals[i - 1]) * (1 + val1_vals[i])) ** (1 / sr_no_vals[i]) 
    val2_vals.append(calculated_value)

df['val2'] = val2_vals

在使用numpy数组进行操作时,我们还可以使用numba之类的即时编译器来极大地加快处理大数据的速度。

@numba.jit(nopython=True)
def calc_val2(val1_vals, sr_no_vals):
    val2_vals = [val1_vals[0]]
    for i in range(1, len(sr_no_vals)):
        calculated_value = (((1 + val2_vals[i - 1]) ** sr_no_vals[i - 1]) * (1 + val1_vals[i])) ** (1 / sr_no_vals[i]) 
        val2_vals.append(calculated_value)
    return val2_vals

df['val2'] = calc_val2(val1_vals, sr_no_vals)