pandas 在熊猫中运行总和(无循环)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13878959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:32:16  来源:igfitidea点击:

Running sum in pandas (without loop)

pythonpandas

提问by leo

I'd like to build a running sum over a pandas dataframe. I have something like:

我想在 Pandas 数据帧上构建一个运行总和。我有类似的东西:

10/10/2012:  50,  0
10/11/2012: -10, 90
10/12/2012: 100, -5

And I would like to get:

我想得到:

10/10/2012:  50,  0
10/11/2012:  40, 90
10/12/2012: 140, 85

So every cell should be the sum of itself and all previous cells, how should I do this without using a loop.

所以每个单元格都应该是它自己和所有先前单元格的总和,我应该如何在不使用循环的情况下做到这一点。

回答by Andy Hayden

As @JonClements mentions, you can do this using the cumsumDataFrame method:

正如@JonClements 提到的,您可以使用cumsumDataFrame 方法执行此操作:

from pandas import DataFrame
df = DataFrame({0: {'10/10/2012': 50, '10/11/2012': -10, '10/12/2012': 100}, 1: {'10/10/2012': 0, '10/11/2012': 90, '10/12/2012': -5}})

In [3]: df
Out[3]: 
              0   1
10/10/2012   50   0
10/11/2012  -10  90
10/12/2012  100  -5

In [4]: df.cumsum()
Out[4]: 
              0   1
10/10/2012   50   0
10/11/2012   40  90
10/12/2012  140  85