Reputation: 1059
Assuming I have the following array in Python:
x = np.array(([1,2,3,4],[5,6,7,8],[9,10,11,12]))
x
Which looks like:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
I have an array mu
, which is the mean of each of the columns of array x
mu = x.mean(axis =0)
Which looks like:
array([5., 6., 7., 8.])
Now, I want a new array x_demean
, where the first column gets subtracted by its own mean, second column by its own mean, and so one.
The result should look like:
array([[ -4, -4, -4, -4],
[ 0, 0, 0, 0],
[ 4, 4, 4, 4])
Upvotes: 2
Views: 181
Reputation: 483
You can use simple x - mu
which provides the desired output.
You can use the proper subtract()
method of numpy also. Refer the docs here.
Try this code:
import numpy as np
x1 = np.array(([1,2,3,4],[5,6,7,8],[9,10,11,12]))
mu = x1.mean(axis =0)
x_demean = np.subtract(x1, mu)
print(x_demean) #use x_demean.astype(int) if you want integer array
Upvotes: 2
Reputation: 8033
x-mu
is all you need to get what you want.
If you want output strictly as integers, do (x-mu).astype(int)
Output
array([[-4, -4, -4, -4],
[ 0, 0, 0, 0],
[ 4, 4, 4, 4]])
Upvotes: 3