我担心这可能是一个非常愚蠢的问题。但是我找不到解决方案。 我想在不使用循环的情况下在 python 中执行以下操作,因为我正在处理大型数组。 有什么建议吗?
import numpy as np
a = np.array([1,2,3,..., N]) # arbitrary 1d array
b = np.array([[1,2,3],[4,5,6],[7,8,9]]) # arbitrary 2d array
c = np.zeros((N,3,3))
c[0,:,:] = a[0]*b
c[1,:,:] = a[1]*b
c[2,:,:] = a[2]*b
c[3,:,:] = ...
...
...
c[N-1,:,:] = a[N-1]*b
最佳答案
我的答案只使用 numpy
原语,特别是数组乘法(你想做的有一个名字,它是一个外积)。
由于 numpy
的外部乘法函数的限制,我们必须重新整形结果,但这非常便宜,因为不涉及 ndarray
的数据 block .
% python
Python 2.7.8 (default, Oct 18 2014, 12:50:18)
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> a = np.array((1,2))
>>> b = np.array([[n*m for m in (1,2,3,4,5,6)] for n in (10,100,1000)])
>>> print b
[[ 10 20 30 40 50 60]
[ 100 200 300 400 500 600]
[1000 2000 3000 4000 5000 6000]]
>>> print np.outer(a,b)
[[ 10 20 30 40 50 60 100 200 300 400 500 600
1000 2000 3000 4000 5000 6000]
[ 20 40 60 80 100 120 200 400 600 800 1000 1200
2000 4000 6000 8000 10000 12000]]
>>> print "Almost there!"
Almost there!
>>> print np.outer(a,b).reshape(a.shape[0],b.shape[0], b.shape[1])
[[[ 10 20 30 40 50 60]
[ 100 200 300 400 500 600]
[ 1000 2000 3000 4000 5000 6000]]
[[ 20 40 60 80 100 120]
[ 200 400 600 800 1000 1200]
[ 2000 4000 6000 8000 10000 12000]]]
>>>
关于python - 如何使 1d 数组乘以 2d 数组得到 python 的 3d 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27270530/