问题
Say I have:
a = np.array([[2, 4],
[6, 8]])
b = np.array([[1, 3],
[1, 5]])
I want to get to:
c = np.array([[20,32],
[28, 44]])
where c
is the result of multiplying each column of a
by b
, then summing that result along the first axis.
I.e.:
print(np.sum(a[:, 0] * b, axis=1))
[20 32]
print(np.sum(a[:, 1] * b, axis=1))
[28 44]
Can I do through broadcasting rather than:
- using
np.apply_along_axis
or - looping through each column?
回答1:
You can use np.dot -
b.dot(a).T
Alternatively, using np.einsum (for the kicks maybe) -
np.einsum('ij,ki->jk',a,b)
来源:https://stackoverflow.com/questions/45200611/replace-looping-over-axes-with-broadcasting