Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a 2d numpy array a 3d array?

I have a 2d array with shape (x, y) which I want to convert to a 3d array with shape (x, y, 1). Is there a nice Pythonic way to do this?

like image 867
nobody Avatar asked Sep 10 '11 14:09

nobody


People also ask

How do you make a NumPy 3D array?

A three dimensional means we can use nested levels of array for each dimension. To create a 3-dimensional numpy array we can use simple numpy. array() function to display the 3-d array.


2 Answers

In addition to the other answers, you can also use slicing with numpy.newaxis:

>>> from numpy import zeros, newaxis >>> a = zeros((6, 8)) >>> a.shape (6, 8) >>> b = a[:, :, newaxis] >>> b.shape (6, 8, 1) 

Or even this (which will work with an arbitrary number of dimensions):

>>> b = a[..., newaxis] >>> b.shape (6, 8, 1) 
like image 69
Mark Dickinson Avatar answered Sep 16 '22 15:09

Mark Dickinson


numpy.reshape(array, array.shape + (1,)) 
like image 37
Winston Ewert Avatar answered Sep 19 '22 15:09

Winston Ewert