本文介绍了如何使用numpy.frompyfunc返回元素,而不是数组的数组的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用从SHTOOLS包PLegendre功能。它返回Legendre多项式为一个特定的参数的阵列。 PLegendre(LMAX,x)返回勒的阵列多项式P_0(x)至P_lmax(x)的。它的工作原理是这样的:

I am using the PLegendre function from the SHTOOLS package. It returns an array of Legendre polynomials for a particular argument. PLegendre(lmax,x) returns an array of Legendre polynomials P_0(x) to P_lmax(x). It works like this:

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。

I would like to pass an array as a parameter, so I use 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)

的输出是一个数组的数组。我明白,我可以切片阵列创建这个元素的数组。

The output is an array of arrays. I understand that I can create an array of elements from this by slicing the array.

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.        ]])

但是...有没有办法让这个直接,而不必切片数组的数组?

But.. is there a way to get to this directly, instead of having to slice the array of arrays?

推荐答案

我觉得它不能直接完成前面已经指出的 在 np.vectorize 哪做几乎同样的事情的情况。请注意,code不是通过使用更快的再普通的循环 np.frompyfunc 的... code不仅看起来更好。

I think it can not be done directly as already pointed out here in the case of np.vectorize which does almost the same thing. Note that your code is not faster then an ordinary for loop by using np.frompyfunc ... the code only looks nicer.

然而,你可以用做什么 np.vstack 而不是列表COM prehension

However, what you can do is using np.vstack instead of the list comprehension

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

这篇关于如何使用numpy.frompyfunc返回元素,而不是数组的数组的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 12:42
查看更多