简体   繁体   English

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

[英]Numpy: Divide each row by a vector element

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 data along 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?长话短说:如何使用对应于每一行的一维标量数组对二维数组的每一行执行操作?

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

As has been mentioned, slicing with None or with np.newaxes is a great way to do this.如前所述,使用Nonenp.newaxes切片是一个很好的方法。 Another alternative is to use transposes and broadcasting, as in另一种选择是使用转置和广播,如

(data.T - vector).T

and

(data.T / vector).T

For higher dimensional arrays you may want to use the swapaxes method of NumPy arrays or the NumPy rollaxis function.对于更高维的数组,您可能需要使用 NumPy 数组的swapaxes方法或 NumPy rollaxis函数。 There really are a lot of ways to do this.确实有很多方法可以做到这一点。

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

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:数据和向量中的列数不应匹配

JoshAdel's solution uses np.newaxis to add a dimension. JoshAdel 的解决方案使用 np.newaxis 添加维度。 An alternative is to use reshape() to align the dimensions in preparation for broadcasting .另一种方法是使用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/vector is ok, but it doesn't get you the answer that you want.请注意, data/vector是可以的,但它不会为您提供您想要的答案。 It divides each column of array (instead of each row ) by each corresponding element of vector .它将array每一(而不是每一)除以vector每个对应元素。 It's what you would get if you explicitly reshaped vector to be 1x3 instead of 3x1 .如果您明确地将vector重塑为1x3而不是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]])

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 .这会将您的向量变成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.至少对我来说,这是最直观的方法,因为(在大多数情况下)numpy 只会使用相同内部存储器的视图来重塑它也很有效。

The key is to reshape the vector of size (3,) to (3,1): divide each row by an element or (1,3): divide each column by an element.关键是将大小为 (3,) 的向量重塑为 (3,1):将每行除以一个元素或 (1,3):将每列除以一个元素。 As data.shape does not correspond to vector.shape, NumPy automatically expands vector's shape to (3,3) and performs division, element-wise.由于 data.shape 与 vector.shape 不对应,NumPy 会自动将 vector 的形状扩展为 (3,3) 并按元素执行除法。

In[1]: data/vector.reshape(-1,1)
Out[1]:
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])

In[2]: data/vector.reshape(1,-1)
Out[2]:
array([[1.        , 0.5       , 0.33333333],
       [2.        , 1.        , 0.66666667],
       [3.        , 1.5       , 1.        ]])

Similar:相似的:

x = np.arange(9).reshape(3,3)
x
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

x/np.sum(x, axis=0, keepdims=True)
array([[0.        , 0.08333333, 0.13333333],
       [0.33333333, 0.33333333, 0.33333333],
       [0.66666667, 0.58333333, 0.53333333]])

x/np.sum(x, axis=1, keepdims=True)
array([[0.        , 0.33333333, 0.66666667],
       [0.25      , 0.33333333, 0.41666667],
       [0.28571429, 0.33333333, 0.38095238]])

print(np.sum(x, axis=0).shape)
print(np.sum(x, axis=1).shape)
print(np.sum(x, axis=0, keepdims=True).shape)
print(np.sum(x, axis=1, keepdims=True).shape)
(3,)
(3,)
(1, 3)
(3, 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM