Home > database >  How to reshape a (x, y) numpy array into a (x, y, 1) array?
How to reshape a (x, y) numpy array into a (x, y, 1) array?

Time:06-08

How do you reshape a (55, 11) numpy array to a (55, 11, 1) numpy array?

Attempts:

  • Simply doing numpy_array.reshape(-1, 1) without any loop produces a flat array that is not 3D.
  • The following for loop produces a "cannot broadcast error":
for i in range(len(numpy_array)):
       numpy_array[i] = numpy_array[i].reshape(-1, 1)

CodePudding user response:

Maybe you are looking for numpy.expand_dims(https://numpy.org/doc/stable/reference/generated/numpy.expand_dims.html)?

import numpy
a = numpy.random.rand(55,11)
print(a.shape) # 55,11
print(numpy.expand_dims(a, 2).shape) # 55, 11, 1

CodePudding user response:

Add a newaxis to the array

my_array = np.arange(55*11).reshape(55,11)
my_array.shape
# (55, 11)
# add new axis
new_array = my_array[...,None]
new_array.shape
# (55, 11, 1)

Can specify new shape in reshape too:

new_array = my_array.reshape(*my_array.shape, 1)
new_array.shape
# (55, 11, 1)

CodePudding user response:

One of the answers recommends using expand_dims. That's a good answer, but if you look at its code, and strip off some generalities, all it is doing is:

In [409]: a = np.ones((2,3)); axis=(2,)
     ...: out_ndim = 2 1
     ...: shape_it = iter(a.shape)
     ...: shape = [1 if ax in axis else next(shape_it) for ax in range(out_ndim)]

In [410]: shape
Out[410]: [2, 3, 1]

followed by a return a.reshape(shape).

In other words, the function call is just hiding the obvious, expand a (x,y) to (x,y,1) with

 a.reshape(x,y,1)

Are you seeking some 3d 'magic' akin to the -1 in numpy_array.reshape(-1, 1)?

Personally I like to use None to add dimensions, so prefer the other answer [...,None]. But functionally it's all the same.

  • Related