在 numpy 数组中相乘 [英] Multiplying across in a numpy array

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

问题描述

我正在尝试将二维数组中的每个项乘以一维数组中的相应项.如果我想将每一列乘以一维数组,这很容易,如 所示numpy.multiply 函数.但我想做相反的事情,将行中的每个项相乘.换句话说,我想乘:

[1,2,3] [0][4,5,6] * [1][7,8,9] [2]

并得到

[0,0,0][4,5,6][14,16,18]

但我得到了

[0,2,6][0,5,12][0,8,18]

有谁知道 numpy 是否有一种优雅的方式来做到这一点?非常感谢,亚历克斯

解决方案

像你展示的正态乘法:

<预><代码>>>>将 numpy 导入为 np>>>m = np.array([[1,2,3],[4,5,6],[7,8,9]])>>>c = np.array([0,1,2])>>>米*c数组([[ 0, 2, 6],[ 0, 5, 12],[ 0, 8, 18]])

如果你添加一个轴,它会以你想要的方式相乘:

<预><代码>>>>m * c[:, np.newaxis]数组([[ 0, 0, 0],[ 4, 5, 6],[14, 16, 18]])

您也可以转置两次:

<预><代码>>>>(m.T * c).T数组([[ 0, 0, 0],[ 4, 5, 6],[14, 16, 18]])

I'm trying to multiply each of the terms in a 2D array by the corresponding terms in a 1D array. This is very easy if I want to multiply every column by the 1D array, as shown in the numpy.multiply function. But I want to do the opposite, multiply each term in the row. In other words I want to multiply:

[1,2,3]   [0]
[4,5,6] * [1]
[7,8,9]   [2]

and get

[0,0,0]
[4,5,6]
[14,16,18]

but instead I get

[0,2,6]
[0,5,12]
[0,8,18]

Does anyone know if there's an elegant way to do that with numpy? Thanks a lot, Alex

解决方案

Normal multiplication like you showed:

>>> import numpy as np
>>> m = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> c = np.array([0,1,2])
>>> m * c
array([[ 0,  2,  6],
       [ 0,  5, 12],
       [ 0,  8, 18]])

If you add an axis, it will multiply the way you want:

>>> m * c[:, np.newaxis]
array([[ 0,  0,  0],
       [ 4,  5,  6],
       [14, 16, 18]])

You could also transpose twice:

>>> (m.T * c).T
array([[ 0,  0,  0],
       [ 4,  5,  6],
       [14, 16, 18]])

这篇关于在 numpy 数组中相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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