19

numpy 或 scipy(或其他一些库)中是否有将 cumsum 和 cumprod 的概念推广到任意函数的函数。例如,考虑(理论)函数

cumf( func, array) 

func 是一个接受两个浮点数并返回一个浮点数的函数。特殊情况

lambda x,y: x+y 

lambda x,y: x*y 

分别是 cumsum 和 cumprod。例如,如果

func = lambda x,prev_x: x^2*prev_x 

我将其应用于:

cumf(func, np.array( 1, 2, 3) )

我想

np.array( 1, 4, 9*4 )
4

2 回答 2

13

上面的 ValueError 仍然是使用 Numpy 1.20.1(使用 Python 3.9.1)的错误。

幸运的是,发现了一种使用强制转换的解决方法: https ://groups.google.com/forum/#!topic/numpy/JgUltPe2hqw

import numpy as np
uadd = np.frompyfunc(lambda x, y: x + y, 2, 1)
uadd.accumulate([1,2,3], dtype=object).astype(int)
# array([1, 3, 6])

请注意,由于自定义操作适用于对象类型,因此它不会从 numpy 的高效内存管理中受益。因此,对于非常大的数组,该操作可能比不需要强制转换为对象的操作要慢。

于 2015-01-12T23:11:00.153 回答
12

NumPy 的 ufunc 有accumulate()

In [22]: np.multiply.accumulate([[1, 2, 3], [4, 5, 6]], axis=1)
Out[22]: 
array([[  1,   2,   6],
       [  4,  20, 120]])

不幸的是,调用accumulate()' frompyfunc()ed Python 函数失败并出现一个奇怪的错误:

In [32]: uadd = np.frompyfunc(lambda x, y: x + y, 2, 1)

In [33]: uadd.accumulate([1, 2, 3])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

ValueError: could not find a matching type for <lambda> (vectorized).accumulate, 
            requested type has type code 'l'

这是使用 NumPy 1.6.1 和 Python 2.7.3。

于 2012-12-11T21:14:31.470 回答