pandas 数据框上的累积和函数

编程入门 行业动态 更新时间:2024-10-10 09:15:16
本文介绍了 pandas 数据框上的累积和函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

鉴于一系列的期末金额,我试图获取一个正在运行的"累计金额.

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 数据框上的累积和函数

本文发布于:2023-10-26 06:57:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529407.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   数据   pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!