numpy数组中的多个累积和 [英] Multiple cumulative sum within a numpy array
本文介绍了numpy数组中的多个累积和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是numpy的新手,如果对此问题已经提出,我感到抱歉.我正在寻找一种向量化解决方案,该解决方案可以在一维numpy数组中运行多个不同大小的累积.
I'm sort of newbie in numpy so I'm sorry if this question was already asked. I'm looking for a vectorization solution which enable to run multiple cumsum of different size within a one dimension numpy array.
my_vector=np.array([1,2,3,4,5])
size_of_groups=np.array([3,2])
我想要类似的东西
np.cumsum.group(my_vector,size_of_groups)
[1,3,6,4,9]
我不想要带有循环的解决方案. numpy函数或numpy操作.
I do not want a solution with loops. Either numpy functions or numpy operations.
推荐答案
不确定numpy,但是熊猫可以使用groupby
+ cumsum
轻松地做到这一点:
Not sure about numpy, but pandas can do this pretty easily with a groupby
+ cumsum
:
import pandas as pd
s = pd.Series(my_vector)
s.groupby(s.index.isin(size_of_groups.cumsum()).cumsum()).cumsum()
0 1
1 3
2 6
3 4
4 9
dtype: int64
这篇关于numpy数组中的多个累积和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文