我希望从NxM到NxMx3映射numpy.array
,其中三个元素的向量是原始条目的函数:
lambda x: [f1(x), f2(x), f3(x)]
但是,numpy.vectorize
之类的内容不允许更改尺寸。
当然,我可以创建一个零数组并创建一个循环(and it is what I am doing by now),但它既没有Pythonic也没有效率(如Python中的每个循环)。
有没有更好的方法在numpy.array上执行元素运算,为每个条目生成一个向量?
答案 0 :(得分:4)
如果我理解您的问题,建议您使用np.dstack
:
Docstring:
Stack arrays in sequence depth wise (along third axis).
Takes a sequence of arrays and stack them along the third axis
to make a single array. Rebuilds arrays divided by `dsplit`.
This is a simple way to stack 2D arrays (images) into a single
3D array for processing.
In [1]: a = np.arange(9).reshape(3, 3)
In [2]: a
Out[2]:
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
In [3]: x, y, z = a*1, a*2, a*3 # in your case f1(a), f2(a), f3(a)
In [4]: np.dstack((x, y, z))
Out[4]:
array([[[ 0, 0, 0],
[ 1, 2, 3],
[ 2, 4, 6]],
[[ 3, 6, 9],
[ 4, 8, 12],
[ 5, 10, 15]],
[[ 6, 12, 18],
[ 7, 14, 21],
[ 8, 16, 24]]])
答案 1 :(得分:4)
现在我看到了你的代码,对于大多数简单的数学运算你可以让numpy进行循环,通常被称为 vectorization :
def complex_array_to_rgb(X, theme='dark', rmax=None):
'''Takes an array of complex number and converts it to an array of [r, g, b],
where phase gives hue and saturaton/value are given by the absolute value.
Especially for use with imshow for complex plots.'''
absmax = rmax or np.abs(X).max()
Y = np.zeros(X.shape + (3,), dtype='float')
Y[..., 0] = np.angle(X) / (2 * pi) % 1
if theme == 'light':
Y[..., 1] = np.clip(np.abs(X) / absmax, 0, 1)
Y[..., 2] = 1
elif theme == 'dark':
Y[..., 1] = 1
Y[..., 2] = np.clip(np.abs(X) / absmax, 0, 1)
Y = matplotlib.colors.hsv_to_rgb(Y)
return Y
此代码的运行速度应该比您的快。