我有一个名为phases
的数组,假设它是这样的:
phases = numpy.random.uniform(0,1,10)
我现在要填充一个矩阵,其中每一行都是应用于一个连续的阶段索引的函数,每一列都是它的倍数,如下所示:
[[ f(phases[0]) f(2*phases[0]) f(3*phases[0]) ]
[ f(phases[1]) f(2*phases[1]) f(3*phases[1]) ]
... ... ...
[ f(phases[9]) f(2*phases[9]) f(3*phases[9]) ]]
为了举例,我们可以说
f
是一些简单的东西,比如f
。所以我想我应该使用
f(x) = x+1
如下:numpy.fromfunction(lambda i,j: (j+1)*phases[i]+1,
(phases.size, 3), dtype=float)
但这给了我一个错误:
IndexError: arrays used as indices must be of integer (or boolean) type
如何在
numpy.fromfunction
内访问i
的第phases
个元素?或者这是错误的做法?
最佳答案
不象预期的那样工作,它的文档也有误导性。
函数不是为每个单元格调用的,而是对所有索引调用一次。
def fromfunction(function, shape, **kwargs):
dtype = kwargs.pop('dtype', float)
args = indices(shape, dtype=dtype)
return function(*args,**kwargs)
所以现在,要得到结果,可以执行以下操作:
In [57]: vf = numpy.vectorize(f)
In [58]: vf(numpy.outer(phases, numpy.arange(1,4)))
Out[58]:
array([[ 1.87176928, 2.74353857, 3.61530785],
[ 1.23090955, 1.4618191 , 1.69272866],
[ 1.29294723, 1.58589445, 1.87884168],
[ 1.05863891, 1.11727783, 1.17591674],
[ 1.28370397, 1.56740794, 1.85111191],
[ 1.87210286, 2.74420573, 3.61630859],
[ 1.08652975, 1.1730595 , 1.25958925],
[ 1.33835545, 1.6767109 , 2.01506634],
[ 1.74479635, 2.48959269, 3.23438904],
[ 1.76381301, 2.52762602, 3.29143903]])
numpy.fromfunction
将执行两个向量的外积,这正是除了函数之外您想要的。函数必须能够处理数组。对于非平凡的操作,必须对函数进行矢量化,以便逐单元格应用该函数。在你的例子中,你不必在意。