Home > Back-end >  Is it possible to add a dimension to a numpy.ndarray that its shape becomes (n,m,1)?
Is it possible to add a dimension to a numpy.ndarray that its shape becomes (n,m,1)?

Time:10-19

For example:

xlist = [(1, 2, 3, 4), (5, 6, 7, 8)]
xarr = np.array(xlist)

The shape of xarr is (2,4).

Is it possible to reshape it to (2,4,1), so that I can use xarr[i][j][0] to get an element?

CodePudding user response:

Use:

out = xarr[..., None]

Or:

out = xarr.reshape(2, 4, 1)

Output:

array([[[1],
        [2],
        [3],
        [4]],

       [[5],
        [6],
        [7],
        [8]]])

CodePudding user response:

There are several ways:

xnew = np.rehshape(xnew, (2, 4, 1)) # slow but can handle non numpy
xnew = xarr.reshape((2, 4, 1))      # create a copy
xarr[:,:,np.newaxis]  # (2, 4, 1)   # create a VIEW
xarr.shape = (2, 4, 1)              # fast, changes original array

Some performance test, all operations are invariant for small to medium sized arrays.

enter image description here

  • Related