I have a numpy matrix A where the data is organised column-vector-vise i.e A[:,0] is the first data vector, A[:,1] is the second and so on. I wanted to know whether there was a more elegant way to zero out the mean from this data. I am currently doing it via a for loop:
mean=A.mean(axis=1)
for k in range(A.shape[1]):
A[:,k]=A[:,k]-mean
So does numpy provide a function to do this? Or can it be done more efficiently another way?
As is typical, you can do this a number of ways. Each of the approaches below works by adding a dimension to the
meanvector, making it a 4 x 1 array, and then NumPy’s broadcasting takes care of the rest. Each approach creates a view ofmean, rather than a deep copy. The first approach (i.e., usingnewaxis) is likely preferred by most, but the other methods are included for the record.In addition to the approaches below, see also ovgolovin’s answer, which uses a NumPy matrix to avoid the need to reshape
meanaltogether.For the methods below, we start with the following code and example array
A.Using
numpy.newaxisUsing
NoneThe documentation states that
Nonecan be used instead ofnewaxis. This is becauseTherefore, the following accomplishes the task.
That said,
newaxisis clearer and should be preferred. Also, a case can be made thatnewaxisis more future proof. See also: Numpy: Should I use newaxis or None?Using
ndarray.reshapeChanging
ndarray.shapedirectlyYou can alternatively change the shape of
meandirectly.