Search code examples
pythonnumpymatrixdimension

Numpy : convert 2D array to 3D array


I have a 2 dimensional array : A = numpy.array([[1, 2, 3], [4, 5, 6]]) and would like to convert it to a 3 dimensional array : B = numpy.array([[[1, 2, 3], [4, 5, 6]]])

Is there a simple way to do that ?


Solution

  • Simply add a new axis at the start with np.newaxis -

    import numpy as np
    
    B = A[np.newaxis,:,:]
    

    We could skip listing the trailing axes -

    B = A[np.newaxis]
    

    Also, bring in the alias None to replace np.newaxis for a more compact solution -

    B = A[None]