乘以不同大小的数组

时间:2014-11-24 02:20:35

标签: python numpy

将不同大小的数组相乘。

import numpy as np

a = np.array([1,2,3,4,5])

b = np.array([1,2,3])

print a*b

当然错误:

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

预期结果是np.array([1,4,9,0,0])

怎么办?

3 个答案:

答案 0 :(得分:6)

>>> a = np.array([1,2,3,4,5])
>>> b = np.array([1,2,3])
>>> b.resize(a.shape)
>>> a * b
array([1, 4, 9, 0, 0])

答案 1 :(得分:0)

根据大小的不同,将零数组附加到较小的数组:

import numpy as np

a = np.array([1,2,3,4,5])
b = np.array([1,2,3])

diff = len(a) - len(b)

c = np.append(b, np.zeros(diff))

print a*c

答案 2 :(得分:0)

上面的答案是正确的,但不要在一行中创建临时

c=np.append(a,np.zeros(0 if (len(b) - len(a))<0 else (len(b) - len(a))))*np.append(b,np.zeros(0 if (len(a) - len(b))<0 else (len(a) - len(b))))