This question already has an answer here:
这个问题已经有了答案:
- Multiplying 2d array by 1d array 1 answer
- 用2d数组乘以1d数组1答案
I have an array A
of shape (w,h) = 3000,2000
and another array B
of shape d = 100
我有一个形状为(w,h)的数组A = 3000,2000,还有一个形状为d = 100的数组B
I want to multiply each value of A
by B
, and get the result in the form of an array C
of shape (w,h,d) = 3000,2000,100
我想把A的每个值乘以B,得到一个形状为C的数组(w,h,d) = 3000,2000,100
Right now I am using the very slow code below, how can I vectorize this operation?
现在我正在使用下面非常慢的代码,我如何对这个操作进行矢量化?
w,h,d = 3000,2000,100
A = np.ones((w,h))
B = np.arange(d)
C = np.zeros((w,h,d))
for i in xrange(w):
for j in xrange(h):
C[i,j] = A[i,j] * B
Thank you
谢谢你!
1 个解决方案
#1
5
Use numpy broadcast.
使用numpy广播。
Try this
试试这个
from numpy.random import rand
a = rand(4,5)
b = rand(6)
c = a[...,None] * b
print (c.shape)
Or equivelently
或equivelently
c = a.reshape(4,5,1)*b
#1
5
Use numpy broadcast.
使用numpy广播。
Try this
试试这个
from numpy.random import rand
a = rand(4,5)
b = rand(6)
c = a[...,None] * b
print (c.shape)
Or equivelently
或equivelently
c = a.reshape(4,5,1)*b