如何在 Pandas 数据框中使用先前行的值,当先前的值也是使用分组数据计算得出的?

4

我有这样的数据框:

enter image description here

df = pd.DataFrame({'id': [111,111,111, 222,222,222],\
                   'Date': ['30.04.2020', '31.05.2020', '30.06.2020', \
                            '30.04.2020', '31.05.2020', '30.06.2020'],\
                   'Debt': [100,100,70, 200,200,200] , \
                   'Ear_coef': [0,0.2,0.2, 0,0,0.3]}) 
df['Date'] = pd.to_datetime(df['Date'] ) 
df['Contract'] = pd.DataFrame(df.groupby(['id']).apply(lambda x: x.Debt - x.Debt.shift(1))).reset_index().Debt
# df.groupby(['id']).
df 

我需要得到这样的DataFrame:

enter image description here

起始DataFrame:
  • 第一列是合同id
  • 第二列是日期
  • 第三列是预付款系数(EAR)
  • 第四列是合同付款
结果DataFrame:
  • 第五列是EAR。它等于Ear_coef(t) * Debt_with_EAR(t-1)
  • 第六列是Debt_with_EAR。它等于Debt_with_EAR(t-1)+Contract(t)+EAR(t)
Ear 和 Debt_with_EAR 在第一天的值分别为0和Debt。
我尝试使用apply方法解决此任务,但是由于需要使用先前计算的值,因此我并没有成功。 这些答案对我没有帮助Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?,因为我有成百上千个id。
感谢您的帮助。
1个回答

1

您正在寻找.shift()

然而,.apply() 并不容易适用。一个解决方法是:

df['EAR'] = df['EAR_coef'] * df['Debt with EAR'].shift(1)

对于你最后一列,你可能需要使用 .rolling(),但我不确定你的公式是什么?它似乎没有止境。

你的方法不可行,因为你并不知道所有预测时间段内 df['Debt with EAR'] 的值。例如,对于 id 为 111 的数据,使用你的方法得到的 df['EAR'] = [NaN, 20, NaN] 是不正确的。 - Roman
是的,但这是您的公式存在问题;EAR 依赖于 Debt_with_EAR,而 Debt_with_EAR 又依赖于 EAR - gosuto
当我在第一天描述EarDebt_with_EAR时,它们分别等于0和Debt。但是在第二天,我可以在开始时计算EAR,然后计算Debt_with_EAR - Roman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接