Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 对数据帧最后一行中的所有项求和_Python_Pandas - Fatal编程技术网

Python 对数据帧最后一行中的所有项求和

Python 对数据帧最后一行中的所有项求和,python,pandas,Python,Pandas,我有以下数据帧: 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/

我有以下数据帧:

            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)。

使用
.ix[]
语法选择行,并对结果序列调用
.sum()

In [0]: df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])

In [1]: df
Out[1]: 
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9

In [2]: df.ix[2]
Out[2]: 
0    7
1    8
2    9
Name: 2, dtype: int64

In [3]: df.ix[2].sum()
Out[3]: 24
如果在使用日期时间作为索引值时遇到问题,可以使用
.iloc[]
而不是
.ix[]
,并传递一个整数以按位置而不是按索引值访问行

In [4]: df.index = ['cat', 'dog', 'bear']

In [5]: df
Out[5]: 
      0  1  2
cat   1  2  3
dog   4  5  6
bear  7  8  9

In [6]: df.ix['bear']
Out[6]: 
0    7
1    8
2    9
Name: bear, dtype: int64

In [7]: df.iloc[2]
Out[7]: 
0    7
1    8
2    9
Name: bear, dtype: int64

只需使用iloc[-1]:

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

Out[3]:
-0.0027269999999999985
或:


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

到目前为止您尝试过的代码?使用
sum()
方法对一个轴上的值求和。通过
参数选择哪个轴。因此,要获得所有行的总和,请执行a.sum(axis=1)。如果您只需要一行,可以按照下面kronosapiens的建议选择它。
In [8]:    
df.tail(1).sum(axis=1)

Out[8]:
date
2015-02-23   -0.002727
dtype: float64