如何将numpy 2D数组与numpy 1D数组相乘?

时间:2013-04-26 06:10:00

标签: python numpy

两个数组:

a = numpy.array([[2,3,2],[5,6,1]])
b = numpy.array([3,5])
c = a * b

我想要的是:

c = [[6,9,6],
     [25,30,5]]

但是,我收到了这个错误:

ValueError: operands could not be broadcast together with shapes (2,3) (2)

如何乘以带有1D数组的nD数组,其中len(1D-array) == len(nD array)

2 个答案:

答案 0 :(得分:21)

您需要将数组b转换为(2,1)形状数组,在索引元组中使用None或numpy.newaxis

import numpy
a = numpy.array([[2,3,2],[5,6,1]])
b = numpy.array([3,5])
c = a * b[:, None]

这是document

答案 1 :(得分:2)

另一个策略是reshape 第二个数组,因此它与第一个数组具有相同的维数:

c = a * b.reshape((b.size, 1))
print(c)
# [[ 6  9  6]
#  [25 30  5]]

或者,可以就地修改第二个数组的shape属性:

b.shape = (b.size, 1)
print(a.shape)  # (2, 3)
print(b.shape)  # (2, 1)
print(a * b)
# [[ 6  9  6]
#  [25 30  5]]