[英]Apply a function to dataframe which includes previous row data
[英]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.