用广播替换环行循环 [英] Replace looping-over-axes with broadcasting

查看:91
本文介绍了用广播替换环行循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有

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

我想去

c = np.array([[20,32],
              [28, 44]])

其中c是将a的每一列乘以b,然后沿第一轴求和的结果.

where c is the result of multiplying each column of a by b, then summing that result along the first axis.

即:

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:

  • 使用np.apply_along_axis
  • 遍历每一列?

推荐答案

您可以使用 np.dot -

You can use np.dot -

b.dot(a).T

或者,使用 np.einsum (也许是踢踢的)-

Alternatively, using np.einsum (for the kicks maybe) -

np.einsum('ij,ki->jk',a,b)

这篇关于用广播替换环行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆