numpy的:用一个矢量元素除以每行 [英] Numpy: Divide each row by a vector element

查看:1992
本文介绍了numpy的:用一个矢量元素除以每行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个numpy的数组:

Suppose I have a numpy array:

data = np.array([[1,1,1],[2,2,2],[3,3,3]])

和我有一个相应的矢量

vector = np.array([1,2,3])

如何在数据沿每一行操作要么减去或划分所以结果是:

How do I operate on data along each row to either subtract or divide so the result is:

sub_result = [[0,0,0], [0,0,0], [0,0,0]]
div_result = [[1,1,1], [1,1,1], [1,1,1]]

长话短说:我如何与标量的一维数组对应于各行的二维数组的每一行执行操作

Long story short: How do I perform an operation on each row of a 2D array with a 1D array of scalars that correspond to each row?

推荐答案

在这里你去。你只需要使用(或者 np.newaxis )联合广播:

Here you go. You just need to use None (or alternatively np.newaxis) combined with broadcasting:

In [6]: data - vector[:,None]
Out[6]:
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

In [7]: data / vector[:,None]
Out[7]:
array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])

这篇关于numpy的:用一个矢量元素除以每行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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