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 ?

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

Comments

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]]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.