user8182249
user8182249

Reputation: 83

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 ?

Upvotes: 3

Views: 1650

Answers (2)

rayryeng
rayryeng

Reputation: 104474

It is also possible to create a new NumPy array by using the constructor so that it takes in a list. This list contains a single element which is the array A and it will allow you to create same array with the singleton dimension being the first one. The result would be the 3D array you desire:

B = numpy.array([A])

Example Output

In [13]: import numpy as np

In [14]: A = np.array([[1, 2, 3], [4, 5, 6]])

In [15]: B = np.array([A])

In [16]: B
Out[16]:
array([[[1, 2, 3],
        [4, 5, 6]]])

Upvotes: 1

Divakar
Divakar

Reputation: 221524

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]

Upvotes: 4

Related Questions