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

查看:63
本文介绍了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的ufunc具有

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天全站免登陆