0

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?

0

2 Answers 2

8

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.

0
2

To do this kind of calculations you should use numpy.

Assuming that a is your starting array:

a.transpose()

would do the trick

3
  • Is there a difference between a.T and a.transpose() that you know of?
    – mgilson
    Commented May 31, 2012 at 12:32
  • I thought they would be, but I figured that I'd ask to make sure one didn't return a copy while the other returned a view or something...
    – mgilson
    Commented May 31, 2012 at 12:37
  • Both .T and .transpose() return a view. (I deleted my comment because I thought I was mistaken, but I wasn't: they're entirely the same.)
    – Fred Foo
    Commented May 31, 2012 at 13:27

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.