数组和向量的numpy逐元素乘法 [英] numpy element-wise multiplication of an array and a vector

查看:99
本文介绍了数组和向量的numpy逐元素乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

a =  # multi-dimensional numpy array
ares = # multi-dim array, same shape as a
a.shape
>>> (45, 72, 37, 24)  # the relevant point is that all dimension are different
v = # 1D numpy array, i.e. a vector
v.shape
>>> (37)  # note that v has the same length as the 3rd dimension of a
for i in range(37):
    ares[:,:,i,:] = a[:,:,i,:]*v[i]

我认为必须使用numpy进行压缩,但是我还没有弄清楚.我想我可以复制v然后计算 a * v ,但是我想还有比这更好的东西.因此,可以这么说,我需要在给定的轴上"进行元素明智的乘法.有人知道我该怎么做吗?谢谢.(顺便说一句,我确实找到了一个非常重复的问题,但是由于OP那里特定问题的性质,讨论非常简短,并且被跟踪到其他问题中.)

I'm thinking there has to be a more compact way to do this with numpy, but I haven't figured it out. I guess I could replicate v and then calculate a*v, but I am guessing there is something better than that too. So I need to do element wise multiplication "over a given axis", so to speak. Anyone know how I can do this? Thanks. (BTW, I did find a close duplicate question, but because of the nature of the OP's particular problem there, the discussion was very short and got tracked into other issues.)

推荐答案

您可以转置该数组以交换轴您想要在外面,相乘,然后转置回去:

You can automatically broadcast the vector against the outermost axis of an array. So, you can transpose the array to swap the axis you want to the outside, multiply, then transpose it back:

ares = (a.transpose(0,1,3,2) * v).transpose(0,1,3,2)

这篇关于数组和向量的numpy逐元素乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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