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

后端 未结 8 1658
小鲜肉
小鲜肉 2020-12-08 02:24

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?

8条回答
  •  时光说笑
    2020-12-08 03:27

    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)
    

提交回复
热议问题