累计将操作应用于pandas DataFrame中的连续行 [英] Cumulatively applying an operation to successive rows in a pandas DataFrame

查看:208
本文介绍了累计将操作应用于pandas DataFrame中的连续行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫 DataFrame ,看起来像以下内容:

I have a pandas DataFrame that looks like the following:

sample = pd.DataFrame([[2,3],[4,5],[6,7],[8,9]],
                      index=pd.date_range('2017-08-01','2017-08-04'),
                      columns=['A','B'])

             A   B
2017-08-01   2   3
2017-08-02   4   5
2017-08-03   6   7
2017-08-04   8   9

我想将值沿列累加。以 A 列为例,第二行变为 2 * 4 ,第三行变为 2 * 4 * 6 ,最后一行变为 2 * 4 * 6 * 8 。因此,所需的结果是:

I'd like to cumulatively multiply the values down the columns. Using column A as an example, the second row becomes 2*4, the third row becomes 2*4*6, and the last row becomes 2*4*6*8. Same for column B. So, the desired result is:

             A    B
2017-08-01   2    3
2017-08-02   8    15
2017-08-03   48   105
2017-08-04   384  945

必须有一些内置方法来执行此操作,但是由于链式分配问题,即使使用for循环也遇到了问题。

There must be some built-in way to do this, but I'm having issues even doing it with for loops due to chained assignment issues.

推荐答案

使用 DataFrame.cumprod

out = sample.cumprod()
print(out)
              A    B
2017-08-01    2    3
2017-08-02    8   15
2017-08-03   48  105
2017-08-04  384  945






您也可以使用 np。 cumprod 的值:

sample[:] = np.cumprod(sample.values, axis=0)
print(sample)
              A    B
2017-08-01    2    3
2017-08-02    8   15
2017-08-03   48  105
2017-08-04  384  945






最后,使用 itertools.accumulate (只是为了好玩):


Finally, using itertools.accumulate (just for fun):

from itertools import accumulate
from operator import mul

pd.DataFrame(np.column_stack([
                 list(accumulate(sample[c], mul)) for c in sample.columns]), 
             index=sample.index, 
             columns=sample.columns)

              A    B
2017-08-01    2    3
2017-08-02    8   15
2017-08-03   48  105
2017-08-04  384  945

这篇关于累计将操作应用于pandas DataFrame中的连续行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆