基于行索引的条件Pandas-lambda函数

2024-10-01 22:35:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过引用三列将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

Tags: 数据lambda函数答案dataframedfifshift
2条回答

这样行吗?在这个解决方案中,我使用x.name来获取行索引。在

df['Cumulative Total'] = df.apply(lambda x: x['Total'] if x.name == 0 else x.shift()['Cumulative Total']-(x.shift()['Total']*(x.shift()['Annualized Rate']/1200)),axis=1)

也许是这个?在

df = df.assign(
    Cumulative_Total=df['Total'].iat[0] 
                     - ((df['Total'] * df['Annualized Rate'].div(1200))
                        .shift()
                        .fillna(0)
                        .cumsum())
)

>>> df
   Total  Annualized Rate  Cumulative_Total
0    869        11.047181               869
1    868         5.529954               861
2    871         8.266361               857
3    873         6.872852               851
4    873         8.247423               846
5    874         9.610984               840
6    870         5.517241               833
7    871         8.266361               829
8    868         2.764977               823

相关问题 更多 >

    热门问题