在numpy的阵列跨乘以 [英] Multiplying across in a numpy array

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

问题描述

我试图通过一维数组对应的条款乘以每个术语的二维数组。这是很容易的,如果我想用一维数组乘以每一列,如图所示 numpy.multiply 功能。但是,我想要做的对面,乘行中的每个词。
换句话说,我要乘:

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]

和取得

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

而是我得到

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

有谁知道,如果有一个优雅的方式来做到这一点与numpy的?
非常感谢,
亚历克斯

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]])

您也可以转两次:

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

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

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