Reputation: 1423
Multiply array of different size.
import numpy as np
a = np.array([1,2,3,4,5])
b = np.array([1,2,3])
print a*b
Ofcourse error:
ValueError: operands could not be broadcast together with shapes (5,) (3,)
Expected result is np.array([1,4,9,0,0])
How to do?
Upvotes: 2
Views: 3811
Reputation: 304157
>>> 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])
Upvotes: 6
Reputation: 4868
The above answer is correct but to do it without creating a temporary in one line
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))))
Upvotes: 0
Reputation: 604
Append a zero array to the smaller array depending on the difference in size:
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
Upvotes: 0