Reputation: 287
I would like to reshape the following numpy array in iPython:
array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]]) # Array A
to:
array([[1, 5, 9],[2, 6, 10],[3, 7, 11],[4, 8, 12]]) # Array B
The main task is to calculate the mean of the first elements of Array A (meaning the mean of 1,5,9), then the second elements, etc.
I thought the easiest way to do this is to reshape the array and afterwards calculating the mean of it.
Is there any way to do this without looping through the array via a for
loop?
Upvotes: 0
Views: 1652
Reputation: 363487
Use the axis
keyword on mean
; no need to reshape
:
>>> A = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]])
>>> A.mean(axis=0)
array([ 5., 6., 7., 8.])
If you do want the array B
out, then you need to transpose the array, not reshape it:
>>> A.T
array([[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]])
But then you'd need to give axis=1
to mean
.
Upvotes: 8
Reputation: 10008
To do this kind of calculations you should use numpy.
Assuming that a is your starting array:
a.transpose()
would do the trick
Upvotes: 2