1

How can I transpose vector with numpy? I am trying

import numpy as np
center = np.array([1,2])
center_t = np.transpose(center)

But it doesn't work, how can I do it?

Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
  • Possible duplicate of [Transposing a NumPy array](https://stackoverflow.com/questions/5954603/transposing-a-numpy-array) – iacob Mar 03 '19 at 12:26
  • If you want a column vector start with a row vector. Your `center` is a 1d array. – hpaulj Mar 03 '19 at 12:58

3 Answers3

1

Reshape should do the trick.

center = np.array([1,2])

print(center.reshape(-1,1))

array([[1], [2]])

However, for n-dimensional arrays, this will transpose the array.

print(center.T)

For example:

a = np.array([['a','b','c'],['d','e','f'],['g','h','i']])


print(a)

array([['a', 'b', 'c'],
       ['d', 'e', 'f'],
       ['g', 'h', 'i']], dtype='<U1')

print(a.T)

array([['a', 'd', 'g'],
       ['b', 'e', 'h'],
       ['c', 'f', 'i']], dtype='<U1')
Prometheus
  • 1,148
  • 14
  • 21
0

To transpose an array, a matrix, data needs to have two dimensions. Here your data is 1D.

You can use np.vstack to obtain a two dimension vertical array/matrix from a 1D array/matrix. np.hstack is its horizontal equivalent.

import numpy as np
center = np.array([1,2])
center_t = np.vstack(center)    
Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
  • `vstack` does a lot of work to simply change a (2) shape into a (2,1) shape. It makes 2 (1,1) arrays and concatenates them. – hpaulj Mar 03 '19 at 12:54
  • `np.atleast_2d(center).T` will do the same thing, but more directly. – hpaulj Mar 03 '19 at 21:15
0

The transposition of a 1D array is itself, a 1D array. Unfortunately, it is working precisely how it is meant to.

Please see this.

import numpy as np
a = np.array([5,4])[np.newaxis]
print(a)
print(a.T)

np.newaxis essentially just increases the dimension of the array, so that you're transposing a 2D array, as you would be in Matlab.

smollma
  • 239
  • 3
  • 12