3

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 ?

rayryeng
  • 102,964
  • 22
  • 184
  • 193
user8182249
  • 83
  • 2
  • 7

2 Answers2

4

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]
Divakar
  • 218,885
  • 19
  • 262
  • 358
1

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]]])
rayryeng
  • 102,964
  • 22
  • 184
  • 193