CalmaKarma
CalmaKarma

Reputation: 61

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

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?

Upvotes: 1

Views: 40

Answers (3)

Daraan
Daraan

Reputation: 3790

There are several ways:

xnew = np.rehshape(xnew, (2, 4, 1)) # slow but can handle non numpy
xnew = xarr.reshape((2, 4, 1))      # can create a VIEW
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

Upvotes: 2

Daniel F
Daniel F

Reputation: 14399

You can use np.atleast_3d in this case. As a bonus, it will also handle 1-d arrays (although a n-length 1d array will end up with shape (1,n,1) - which is probably what you'd want in this case anyway)

np.atleast_3d(xarr).shape
Out[]: (2, 4, 1)

Upvotes: 1

mozway
mozway

Reputation: 260790

Use:

out = xarr[..., None]

Or:

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

Output:

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

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

Upvotes: 2

Related Questions