本文介绍了当在apply中也计算出前一个值时,Pandas中有没有一种方法可以使用dataframe.apply中的前一个行值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

 Index_Date    A    B    C    D
 ===============================
 2015-01-31    10   10   Nan  10
 2015-02-01     2    3   Nan  22 
 2015-02-02    10   60   Nan  280
 2015-02-03    10   100   Nan  250

要求:

 Index_Date    A    B    C    D
 ===============================
 2015-01-31    10   10   10   10
 2015-02-01     2    3   23   22
 2015-02-02    10   60   290  280
 2015-02-03    10   100  3000 250

通过获取Dvalue来为2015-01-31导出

Column C.

Column C is derived for 2015-01-31 by taking value of D.

然后我需要将Cvalue用于2015-01-31,并乘以2015-02-01上的Avalue并添加B.

Then I need to use the value of C for 2015-01-31 and multiply by the value of A on 2015-02-01 and add B.

通过if else我尝试了applyshift,这会导致键错误.

I have attempted an apply and a shift using an if else by this gives a key error.

推荐答案

首先,创建派生值:

df.loc[0, 'C'] = df.loc[0, 'D']

然后遍历其余行并填充计算出的值:

Then iterate through the remaining rows and fill the calculated values:

for i in range(1, len(df)):
    df.loc[i, 'C'] = df.loc[i-1, 'C'] * df.loc[i, 'A'] + df.loc[i, 'B']


  Index_Date   A   B    C    D
0 2015-01-31  10  10   10   10
1 2015-02-01   2   3   23   22
2 2015-02-02  10  60  290  280

这篇关于当在apply中也计算出前一个值时,Pandas中有没有一种方法可以使用dataframe.apply中的前一个行值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 18:44