Skip to main content
 首页 » 编程设计

python之对数据框最后一行中的所有项目求和

2025年05月04日8wayfarer

我有以下数据框:

            BBG.XSWX.KABN.S BBG.XETR.TKA.S  BBG.XSWX.CON.S  BBG.XLON.ISAT.S 
date                 
20/02/2015  -0.004881       0.008011        0.007047       -0.000307 
20/02/2015  -0.004881       0.008011        0.007047       -0.000307 
17/02/2015  -0.005821      -0.016792       -0.016111        0.001028 
18/02/2015   0.000588       0.019169       -0.000307       -0.001832 
23/02/2015   0.007468      -0.011277       -0.003273        0.004355 

如何对数据框最后一行中的所有项目求和(因此在本例中我得到 -0.002727,等于 0.007468 + -0.011277 + -0.003273 + 0.004355)。

请您参考如下方法:

只需使用iloc[-1]:

In [3]:     
df.iloc[-1].sum() 
 
Out[3]: 
-0.0027269999999999985 

或tail :

In [8]:     
df.tail(1).sum(axis=1) 
 
Out[8]: 
date 
2015-02-23   -0.002727 
dtype: float64 

sum 需要 axis=1 的原因是 tail 返回 df 而 iloc[-1] 返回一个系列。