Changing numpy array dimension: from 1d to 2d

Tags:

Method 1. Using [np.newaxis].

In [28]: a = np.array([5, 4])

In [29]: a
Out[29]: array([5, 4])

In [30]: a[np.newaxis]
Out[30]: array([[5, 4]])

In [31]: a[np.newaxis].T
Out[31]: 
array([[5],
       [4]])

In [35]: a[:, np.newaxis]
Out[35]: 
array([[5],
       [4]])

Method 2. Using None.

In [32]: a
Out[32]: array([5, 4])

In [33]: a[:, None]
Out[33]: 
array([[5],
       [4]])

In [34]: a[None].T
Out[34]: 
array([[5],
       [4]])

Method 3. Using reshape.

In [51]: a = np.array([5, 4])

# If a shape is -1, the value is inferred.
In [52]: a.reshape((-1, 1))
Out[52]: 
array([[5],
       [4]])

Method 4. Using expand_dims.

In [2]: x = np.array([1, 2])

In [4]: np.expand_dims(x, axis=0)
Out[4]: array([[1, 2]])

In [5]: np.expand_dims(x, axis=1)
Out[5]: 
array([[1],
       [2]])