Python Numpy:将每一行除以一个向量元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19602187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:09:26  来源:igfitidea点击:

Numpy: Divide each row by a vector element

pythonarraysnumpyscipy

提问by BFTM

Suppose I have a numpy array:

假设我有一个 numpy 数组:

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

and I have a corresponding "vector:"

我有一个相应的“向量:”

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

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

我如何data沿着每一行进行减法或除法运算,结果是:

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?

长话短说:如何使用对应于每一行的一维标量数组对二维数组的每一行执行操作?

采纳答案by JoshAdel

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

干得好。您只需要使用None(或替代np.newaxis)与广播结合使用:

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

回答by IanH

As has been mentioned, slicing with Noneor with np.newaxesis a great way to do this. Another alternative is to use transposes and broadcasting, as in

如前所述,切片 withNone或 withnp.newaxes是实现此目的的好方法。另一种选择是使用转置和广播,如

(data.T - vector).T

and

(data.T / vector).T

For higher dimensional arrays you may want to use the swapaxesmethod of NumPy arrays or the NumPy rollaxisfunction. There really are a lot of ways to do this.

对于更高维的数组,您可能需要使用swapaxesNumPy 数组的方法或 NumPyrollaxis函数。确实有很多方法可以做到这一点。

For a fuller explanation of broadcasting, see http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

有关广播的更完整说明,请参阅 http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

回答by stackoverflowuser2010

JoshAdel's solution uses np.newaxis to add a dimension. An alternative is to use reshape() to align the dimensions in preparation for broadcasting.

JoshAdel 的解决方案使用 np.newaxis 添加维度。另一种方法是使用reshape() 来对齐尺寸以准备广播

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

data
# array([[1, 1, 1],
#        [2, 2, 2],
#        [3, 3, 3]])
vector
# array([1, 2, 3])

data.shape
# (3, 3)
vector.shape
# (3,)

data / vector.reshape((3,1))
# array([[1, 1, 1],
#        [1, 1, 1],
#        [1, 1, 1]])

Performing the reshape() allows the dimensions to line up for broadcasting:

执行 reshape() 允许维度排列以进行广播:

data:            3 x 3
vector:              3
vector reshaped: 3 x 1

Note that data/vectoris ok, but it doesn't get you the answer that you want. It divides each columnof array(instead of each row) by each corresponding element of vector. It's what you would get if you explicitly reshaped vectorto be 1x3instead of 3x1.

请注意,这data/vector是可以的,但它不会为您提供您想要的答案。它把各array(而不是每一由每个相应的元素)vector。这是你会得到什么,如果你明确地重塑vector1x3不是3x1

data / vector
# array([[1, 0, 0],
#        [2, 1, 0],
#        [3, 1, 1]])
data / vector.reshape((1,3))
# array([[1, 0, 0],
#        [2, 1, 0],
#        [3, 1, 1]])

回答by shantanu pathak

Pythonic way to do this is ...

Pythonic 的方法是......

np.divide(data.T,vector).T

This takes care of reshaping and also the results are in floating point format. In other answers results are in rounded integer format.

这负责重塑,结果也是浮点格式。在其他答案中,结果采用四舍五入的整数格式。

#NOTE:No of columns in both data and vector should match

#NOTE:数据和向量中的列数不应匹配

回答by meow

Adding to the answer of stackoverflowuser2010, in the general case you can just use

添加到stackoverflowuser2010的答案中,在一般情况下您可以使用

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

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

data / vector.reshape(-1,1)

This will turn your vector into a column matrix/vector. Allowing you to do the elementwise operations as you wish. At least to me, this is the most intuitive way going about it and since (in most cases) numpy will just use a view of the same internal memory for the reshaping it's efficient too.

这会将您的矢量变成column matrix/vector. 允许您根据需要进行元素操作。至少对我来说,这是最直观的方法,因为(在大多数情况下)numpy 只会使用相同内部存储器的视图来重塑它也很有效。