简体   繁体   中英

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. I want to transform it into another 2D arrays according to the following statements:

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.

You can fix this up by supplying the keepdims argument to numpy.mean :

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

If that hadn't existed, an alternative would have been to use reshape .

Gareht McCaughan's solution is more elegant, but in the case keepdims did not exist, you could add a new axis to M :

B = A - M[:, None]

(M[:, None].shape is (2, 1), so broadcasting happens)

You can use the functions subtract and divide from numpy . 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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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