0

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

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.