鉴于一系列的期末金额,我试图获取一个正在运行的"累计金额.
I am attempting to capture a "running" cumulative sum given a series of period amounts.
查看示例:
df = df[1:4].cumsum() # this doesn't return the desired result
推荐答案
您正在寻找axis参数.许多Pandas函数都使用此参数来跨列或跨行应用操作.使用axis=0逐行应用,使用axis=1逐列应用.该操作实际上是遍历列,因此您需要axis=1.
You're looking for the axis parameter. Many Pandas functions take this argument to apply an operation across the columns or across the rows. Use axis=0 to apply row-wise and axis=1 to apply column-wise. This operation is actually traversing the columns, so you want axis=1.
df.cumsum(axis=1)本身可用于您的示例以生成输出表.
df.cumsum(axis=1) by itself works on your example to produce the output table.
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不过,我怀疑您有兴趣将列限制为特定范围.为此,您可以将.loc与列标签(我的字符串)一起使用.
I suspect you're interested in restricting to a specific range of columns, though. To do that, you can use .loc with the column labels (strings in mine).
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.loc基于标签,并且包含边界.如果您想了解有关在Pandas中建立索引的更多信息,请查看 docs
.loc is label-based and is inclusive of the bounds. If you want to find out more about indexing in Pandas, check the docs.
更多推荐
pandas 数据框上的累积和函数
发布评论