How to add a new axis to transform a matrix of shape (n,) to (n,1) with numpy in python ?

Published: March 12, 2021

Tags: Python; Numpy;

DMCA.com Protection Status

Example of how to add a new axis to transform a matrix of shape (n,) to (n,1) with numpy in python:

Create a matrix with numpy

Let's first create a matrix of one dimension:

import numpy as np

A = np.arange(10)

returns

[0 1 2 3 4 5 6 7 8 9]

Then the shape of matrix A is:

A.shape

 (10,)

Add a new axis with numpy.newaxis

To add a new axis, a solution is to use numpy.newaxis:

A = A[:,np.newaxis]

Then if we now check the shape of matrix A:

A.shape

returns

(10, 1)

and print(A) returns

[[0]
 [1]
 [2]
 [3]
 [4]
 [5]
 [6]
 [7]
 [8]
 [9]]

Note: it is also possible to do

A = A[np.newaxis,:]

returns then a shape:

(1,10,)

and A

[[[0]
    [1]
    [2]
    [3]
    [4]
    [5]
    [6]
    [7]
    [8]
    [9]]]

Using reshape

Other solution using reshape

A = A.reshape(10,1)

print(A.shape)

returns

(10, 1)

References