繁体   English   中英

将 function 应用于包含上一行的 dataframe

[英]Apply a function to a dataframe which includes the previous row

我有一个日常杂货支出的输入数据框,如下所示:

input_df1

Date        Potatoes    Spinach     Lettuce     
01/01/22      10         47          0
02/01/22      0          22          3
03/01/22      11         0           3
04/01/22      3          9           2
...

我需要应用一个 function,它需要input_df1 + (previous inflated_df2 row * inflation%)来获得inflated_df2 (第一行除外——该月的第一天没有任何通货膨胀效果,与input_df1相同)。

inflated_df2

inflation%    0.01        0.05        0.03
Date          Potatoes    Spinach     Lettuce     
01/01/22      10          47          0
02/01/22      0.10        24.35       3
03/01/22      11.0        1.218       3.09
04/01/22      3.11        9.06        2.093
...

这就是我试图得到的inflated_df2

inflated_df2.iloc[2:3,:] = input_df1.iloc[0:1,:]
inflated_df2.iloc[3:,:] = inflated_df2.apply(lambda x: input_df1[x] + (x.shift(periods=1, fill_value=0)) * x['inflation%'])

您可以使用itertools中的accumulate

from itertools import accumulate

rates = {'Potatoes': 0.01, 'Spinach': 0.05, 'Lettuce': 0.03}
c = list(rates.keys())
r = list(rates.values())

df[c] = list(accumulate(df[c].to_numpy(), lambda bal, val: val+ bal * r))

Output:

>>> df
       Date  Potatoes    Spinach  Lettuce
0  01/01/22  10.00000  47.000000   0.0000
1  02/01/22   0.10000  24.350000   3.0000
2  03/01/22  11.00100   1.217500   3.0900
3  04/01/22   3.11001   9.060875   2.0927

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM