NumPy/SciPy 中的广义累积函数? [英] generalized cumulative functions in NumPy/SciPy?

查看:21
本文介绍了NumPy/SciPy 中的广义累积函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a function in numpy or scipy (or some other library) that generalizes the idea of cumsum and cumprod to arbitrary function. For example, consider the (theoretical) function

cumf( func, array) 

func 是一个函数,它接受两个浮点数,并返回一个浮点数.特殊情况

func is a function that accepts two floats, and returns a float. Particular cases

lambda x,y: x+y 

lambda x,y: x*y 

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

are cumsum and cumprod respectively. For example, if

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

我将其应用于:

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

我愿意

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

推荐答案

NumPy 的 ufuncs 有 accumulate():

NumPy's ufuncs have accumulate():

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

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

Unfortunately, calling accumulate() on a frompyfunc()'ed Python function fails with a strange error:

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.

This is using NumPy 1.6.1 with Python 2.7.3.

这篇关于NumPy/SciPy 中的广义累积函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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