0

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, Stations). Since I only have 1 station's data that dimension would be a 1. However if I could also make the code flexible enough work for say 2 stations that would be great (e.g. changing the dimension size from (428,288) to (214,144,2)) that would be great!

2
  • 2
    Changing from shape (428, 288) to (214, 144, 2) doesn't make sense: you're halving the total number of elements there. Did you want something like (428, 144, 2) instead? Commented Sep 10, 2016 at 17:06
  • Yes that is what I meant! Sorry! 428,144,2 Commented Sep 10, 2016 at 17:47

2 Answers 2

5

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]]])
Sign up to request clarification or add additional context in comments.

Comments

1

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))

1 Comment

np.expand_dims(a, -1) does this kind of reshape, adding a new axis at the end with the -1 parameter. No new functionality, but the newish np.stack uses it to concatenate arrays on any new axis.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.