简体   繁体   English

我如何在Python Numpy中将2D数组和1D数组相减并相除?

[英]How do I subtract and divide a 2D array and a 1D array in Python Numpy?

I have a 2D numpy array defined A, for example. 例如,我有一个2D numpy数组,定义为A。 I want to transform it into another 2D arrays according to the following statements: 我想根据以下语句将其转换为另一个2D数组:

B = A - mean(A), the mean by the second axis
C = B / mean(A)

An example: 一个例子:

>>> import numpy as np
>>> A = np.array([[1, 2, 3], [4, 6, 8]])
>>> A
array([[1, 2, 3],
       [4, 6, 8]])
>>> M = np.mean(A, axis=1)
>>> M
array([ 2.,  6.])
>>> B = ... # ???
>>> B
array([[-1., 0., 1.],
       [-2., 0., 2.]])
>>> C = ... # ???
>>> C
array([[-0.5, 0., 0.5],
       [-0.33333333, 0., 0.33333333]])

Annoyingly, numpy.mean(axis=...) gives you an array where the relevant axis has been deleted rather than set to size 1. So when you apply this to a 2x3 array with axis=1, you get a (rank-1) array of size 2 rather than the 2x1 array you really want. 烦人的是, numpy.mean(axis=...)为您提供了一个数组,其中相关轴已被删除,而不是设置为大小1。因此,当将其应用于axis = 1的2x3数组时,会得到一个(rank- 1)大小为2的数组,而不是您真正想要的2x1数组。

You can fix this up by supplying the keepdims argument to numpy.mean : 您可以通过为keepdims提供keepdims参数来解决此numpy.mean

M = np.mean(A, axis=1, keepdims=True)

If that hadn't existed, an alternative would have been to use reshape . 如果不存在,则可以使用reshape

Gareht McCaughan's solution is more elegant, but in the case keepdims did not exist, you could add a new axis to M : Gareht McCaughan的解决方案更为优雅,但在不存在keepdims的情况下,可以向M添加新轴:

B = A - M[:, None]

(M[:, None].shape is (2, 1), so broadcasting happens) (M [:, None] .shape为(2,1),所以会进行广播)

You can use the functions subtract and divide from numpy . 您可以使用numpy subtractdivide功能。 Solving your example: 解决您的示例:

import numpy as np
A = np.array([[1, 2, 3], [4, 6, 8]])
M = np.mean(A, axis=1)
B = np.subtract(A.T,M).T
C = np.divide(B.T,M).T
print(B)
print(C)

, results in: , 结果是:

[[-1.  0.  1.]
 [-2.  0.  2.]]
[[-0.5         0.          0.5       ]
 [-0.33333333  0.          0.33333333]]

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

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