Numpy transpose of 1D array not giving expected result

sarbjit picture sarbjit · Aug 9, 2012 · Viewed 29.8k times · Source

I am trying a very basic example in Python scipy module for transpose() method but it's not giving expected result. I am using Ipython with pylab mode.

a = array([1,2,3]
print a.shape
>> (3,)

b = a.transpose()
print b.shape
>> (3,)

If I print the contents of arrays "a" and "b", they are similar.

Expectation is: (which will be result in Matlab on transpose)

 [1,
  2,
  3]

Answer

jfs picture jfs · Aug 9, 2012

Transpose is a noop for one-dimensional arrays.

Add new axis and transpose:

>>> a[None].T
array([[1],
       [2],
       [3]])
>>> np.newaxis is None
True

Or reshape:

>>> a.reshape(a.shape+(1,))
array([[1],
       [2],
       [3]])

Or as @Sven Marnach suggested in comments, add new axis at the end:

>>> a[:,None]
array([[1],
       [2],
       [3]])