How to add a dimension to a numpy array in Python

前端 未结 2 604
孤街浪徒
孤街浪徒 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条回答
  •  长情又很酷
    2021-01-27 17:46

    1) To add a dimension to an array a of arbitrary dimensionality:

    b = numpy.reshape (a, list (numpy.shape (a)) + [1])
    

    Explanation:

    You get the shape of a, turn it into a list, concatenate 1 to that list, and use that list as the new shape in a reshape operation.

    2) To specify subdivisions of the dimensions, and have the size of the last dimension calculated automatically, use -1 for the size of the last dimension. e.g.:

    b = numpy.reshape(a, [numpy.size(a,0)/2, numpy.size(a,1)/2, -1])
    

    The shape of b in this case will be [214,144,4].


    (obviously you could combine the two approaches if necessary):

    b = numpy.reshape (a, numpy.append (numpy.array (numpy.shape (a))/2, -1))
    

提交回复
热议问题