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

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

阅读 12.2k
1 个回答
df['total'] = df['volume'].cumsum()
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题