python - 如何使用 numpy.frompyfunc 返回元素数组而不是数组数组?

标签 python arrays numpy numpy-ufunc

我正在使用 SHTOOLS 包中的 PLegendre 函数。它返回特定参数的勒让德多项式数组。 PLegendre(lmax,x) 返回勒让德多项式 P_0(x) 到 P_lmax(x) 的数组。它是这样工作的:

In [1]: from pyshtools import PLegendre
loading shtools documentation

In [2]: import numpy as np

In [3]: PLegendre(3,0.5)
Out[3]: array([ 1.    ,  0.5   , -0.125 , -0.4375])

我想传递一个数组作为参数,所以我使用 frompyfunc。

In [4]: legendre=np.frompyfunc(PLegendre,2,1)

In [5]: legendre(3,np.linspace(0,1,4))
Out[5]: 
array([array([ 1. ,  0. , -0.5, -0. ]),
   array([ 1.        ,  0.33333333, -0.33333333, -0.40740741]),
   array([ 1.        ,  0.66666667,  0.16666667, -0.25925926]),
   array([ 1.,  1.,  1.,  1.])], dtype=object)

输出是一个数组数组。我知道我可以通过对数组进行切片来创建一个元素数组。

In [6]: a=legendre(3,np.linspace(0,1,4))

In [7]: array([a[i][:] for i in xrange(4)])
Out[7]: 
array([[ 1.        ,  0.        , -0.5       , -0.        ],
   [ 1.        ,  0.33333333, -0.33333333, -0.40740741],
   [ 1.        ,  0.66666667,  0.16666667, -0.25925926],
   [ 1.        ,  1.        ,  1.        ,  1.        ]])

但是..有没有办法直接做到这一点,而不必对数组的数组进行切片?

最佳答案

我认为不能像已经指出的那样直接完成herenp.vectorize 的情况下,它做几乎相同的事情。请注意,您的代码并不比使用 np.frompyfunc 的普通 for 循环更快……代码只是看起来更好。

但是,您可以使用 np.vstack 而不是列表理解

a = legendre(3,np.linspace(0,1,4))
np.vstack(a)

关于python - 如何使用 numpy.frompyfunc 返回元素数组而不是数组数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29692875/

相关文章:

python - 在没有 dtype 参数的情况下调用 np.array 会引发错误吗?

python - 多少面比较合理?

python - Pyplot 的刻度值可以被自动间隔整除吗?

python - 根据另一个数据框的列名和索引值填充数据框

r - 如何创建抛硬币R的功能

Java - 读取并存储在数组中

javascript - 无法使用 jQuery 正确打印 JSON 数组中的数据

矩阵向量运算的Python向量化

Python:如何查找数组 x 中与数组 y 中的元素值接近的元素?

Python。检测矢量方向的变化