Reshaping a numpy array

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?


To do this kind of calculations you should use numpy.

Assuming that a is your starting array:

a.transpose()

would do the trick


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 .

链接地址: http://www.djcxy.com/p/68102.html

上一篇: Numpy是指数组中的每一项

下一篇: 重塑一个numpy数组