本文介绍了Numpy:将每一行除以一个向量元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个 numpy 数组:
Suppose I have a numpy array:
data = np.array([[1,1,1],[2,2,2],[3,3,3]])
我有一个相应的向量:"
and I have a corresponding "vector:"
vector = np.array([1,2,3])
如何对每一行的 data
进行减法或除法运算,结果是:
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?
推荐答案
给你.您只需要将 None
(或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:将每一行除以一个向量元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!