我有一个数组[x1,x2,x3,x4,x5,x6]和另一个数组[y1,y2,y3,... y12]。
我想逐个元素地将两个数组相乘,这样我得到一个数组: [x1 * y1,x2 * y2 .... x1 * y7,x2 * y8 ... x6 * y12]
我认为numpy广播会解决这个问题,但需要它们具有相同的形状。
答案 0 :(得分:2)
np.resize
x = np.array([1, 2, 3])
y = np.array([1, 2, 3, 4, 5, 6])
np.resize(x, y.size) * y
array([ 1, 4, 9, 4, 10, 18])
np.resize
的长度不是y
长度的倍数, x
甚至可以工作。它将继续填充来自x
的值,循环遍历直到达到与y
的长度匹配的长度。
x = np.array([1, 2, 3])
y = np.array([1, 2, 3, 4, 5, 6, 7, 8])
np.resize(x, y.size) * y
array([ 1, 4, 9, 4, 10, 18, 7, 16])
答案 1 :(得分:0)
尝试itertools.cycle
,zip
和listcomp
from itertools import cycle
x = np.arange(1,6)
y = np.arange(1,12)
list(zip(cycle(x), y))
Out[1758]:
[(1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5),
(1, 6),
(2, 7),
(3, 8),
(4, 9),
(5, 10),
(1, 11)]
[i*j for i, j in zip(cycle(x), y)]
Out[1759]: [1, 4, 9, 16, 25, 6, 14, 24, 36, 50, 11]