Pandas数据帧的累积和函数

AME*_*AME 6 python pandas

我试图在给定一系列期间金额的情况下捕获"正在运行"的累积金额.

见例子:

在此输入图像描述

df = df[1:4].cumsum() # this doesn't return the desired result
Run Code Online (Sandbox Code Playgroud)

小智 4

您正在寻找axis参数。许多 Pandas 函数都使用此参数来跨列或跨行应用操作。用于axis=0按行应用和axis=1按列应用。这个操作实际上是遍历列,所以你想要axis=1.

df.cumsum(axis=1)本身适用于您的示例以生成输出表。

In [3]: df.cumsum(axis=1)
Out[3]:
      1   2   3   4
10   16  30  41  61
51   13  29  40  50
13   11  30  45  61
321  12  27  37  52
Run Code Online (Sandbox Code Playgroud)

不过,我怀疑您有兴趣限制特定范围的列。为此,您可以使用.loc列标签(我的字符串)。

In [4]: df.loc[:, '2':'3'].cumsum(axis=1)
Out[4]:
      2   3
10   14  25
51   16  27
13   19  34
321  15  25
Run Code Online (Sandbox Code Playgroud)

.loc是基于标签的并且包含边界。如果您想了解有关 Pandas 索引的更多信息,请查看文档