pandas的DataFrame多行求和问题.

开发环境

python 3.6
pandas 0.23.3

有一个DataFrame,如下表示:

import pandas as pd
arr = [[10,10,1],[22,24.2,1.1],[15,15,1],[9,8.1,0.9],[50,55,1.1]]
df = pd.DataFrame(arr,columns=['volume','amount','price'])
    volume  amount  price
0      10    10.0    1.0
1      22    24.2    1.1
2      15    15.0    1.0
3       9     8.1    0.9
4      50    55.0    1.1

需要volume列每行累加的和,得出total列

    volume  amount  price  total
0      10    10.0    1.0    10.0
1      22    24.2    1.1    32.0
2      15    15.0    1.0    47.0
3       9     8.1    0.9    56.0
4      50    55.0    1.1    106.0

目前我的写法:

for index in df.index:
     num = df[df.index < index]['volume'].sum()
     df.loc['total'] = num

求助各位大神,有没有更好的方法?

GCT1015
浏览 4007回答 1
1回答

交互式爱情

df['total'] = df['volume'].cumsum()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python