How to add a dimension to a numpy array in Python

前端 未结 2 606
孤街浪徒
孤街浪徒 2021-01-27 17:15

I have an array that is size (214, 144). I need it to be (214,144,1) is there a way to do this easily in Python? Basically the dimensions are supposed to be (Days, Times, Statio

2条回答
  •  旧时难觅i
    2021-01-27 17:41

    You could use reshape:

    >>> a = numpy.array([[1,2,3,4,5,6],[7,8,9,10,11,12]])
    >>> a.shape
    (2, 6)
    >>> a.reshape((2, 6, 1))
    array([[[ 1],
            [ 2],
            [ 3],
            [ 4],
            [ 5],
            [ 6]],
    
           [[ 7],
            [ 8],
            [ 9],
            [10],
            [11],
            [12]]])
    >>> _.shape
    (2, 6, 1)
    

    Besides changing the shape from (x, y) to (x, y, 1), you could use (x, y/n, n) as well, but you may want to specify the column order depending on the input:

    >>> a.reshape((2, 3, 2))
    array([[[ 1,  2],
            [ 3,  4],
            [ 5,  6]],
    
           [[ 7,  8],
            [ 9, 10],
            [11, 12]]])
    >>> a.reshape((2, 3, 2), order='F')
    array([[[ 1,  4],
            [ 2,  5],
            [ 3,  6]],
    
           [[ 7, 10],
            [ 8, 11],
            [ 9, 12]]])
    

提交回复
热议问题