我试图通过引用三列将lambda函数应用于dataframe。我想根据以下逻辑更新其中一列Cumulative Total
:
如果它在第一行,那么Cumulative Total
应该等于Total
中的值。
如果不是第一行,则应用以下引用前一行的公式:
x.shift()['Cumulative Total']
- (x.shift()['Total'] * (x.shift()['Annualized Rate'] / 1200))
我希望Cumulative Total
列如下所示:
Total Annualized Rate Cumulative Total
869 11.04718067 869
868 5.529953917 861
871 8.266360505 857
873 6.872852234 851
873 8.24742268 846
874 9.610983982 840
870 5.517241379 833
871 8.266360505 829
868 2.764976959 823
让我困惑的是我如何判断自己是否在第一排。这听起来很琐碎,但我对熊猫很陌生,完全被难住了。iloc
似乎不起作用,因为它似乎只用于获取给定索引的一行。在
目前的代码如下:
df['Cumulative Total'] = df.apply(lambda x: x['Total'] if x.iloc[0] else x.shift()['Cumulative Total']-(x.shift()['Total']*(x.shift()['Annualized Rate']/1200)),axis=1)
语句if x.iloc[0]
错误。你知道我怎么确定是不是第一排吗?在
编辑:感谢大家的回答。亚历山大的答案是正确的,但我注意到结果有点偏离预期。使用的数据帧越大,这些差异就越明显。在
亚历山大-你能用修改你的答案来解决这个问题吗?使用vanilla Python,我得到了下面的结果。这些差异在很大程度上是微不足道的,但如前所述,在较大的数据集中会变得更加明显。在
^{pr2}$退货:
869
860.9999997591667
856.9999996991667
850.99999934
845.9999995100001
839.9999992775
832.9999992641667
828.9999995391668
822.9999991800001
这样行吗?在这个解决方案中,我使用
x.name
来获取行索引。在也许是这个?在
相关问题 更多 >
编程相关推荐