1

I have a 3d numpy table with shape=(2,3,4) like below:

a = np.array([[[1., 2., 3., 4.],
        [1., 2., 3., 4.],
        [1., 2., 3., 4.]],

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

And want to reshape this in a way where the columns in each dimension are stacked into a new column in a 2d matrix.

1  5
1  5
1  5
2  6
2  6
2  6
3  7
3  7
3  7
4  8
4  8
4  8

2 Answers 2

4

Here you go:

res = a.T.reshape((-1,2))

Output:

array([[1., 5.],
       [1., 5.],
       [1., 5.],
       [2., 6.],
       [2., 6.],
       [2., 6.],
       [3., 7.],
       [3., 7.],
       [3., 7.],
       [4., 8.],
       [4., 8.],
       [4., 8.]])
Sign up to request clarification or add additional context in comments.

4 Comments

How can I access the first column? res[:][0] doesnt work. The first column is [1,1,1,2,2,2,3,3,3,4,4,4,4]
you can use res[:,0]
Thanks alot. That was really helpful.
you're welcome. you can mark your questions as answered if you like
2

To reshape a numpy array, use the reshape method.

Basically it looks at the array as it was flattened and works over it with the new given shape. It does however iterates over the last index first, ie, the inner-most list will be processed, then the next and so on.

So both a np.array([1, 2, 3, 4, 5, 6]).reshape((3, 2)) and a np.array([[1, 2, 3], [4, 5, 6]]).reshape((3, 2)) will give [[1, 2], [3, 4], [5, 6]], since these two originating arrays are the same when flattened.

You want a (12, 2) array, or if you read the reshape docs, you can pass (-1, 2) and numpy will figure the other dimension.

So if you just give the new shape for your array as is, it will start working with the first list x[0, 0] = [1, 2, 3, 4], which would become [[1, 2], [3, 4]], ... That's not what you want.

But note that if you transpose your array first, then you'll have the items you want in the inner lists (fast varying index):

In : x.T
Out: 
array([[[1., 5.],
        [1., 5.],
        [1., 5.]],

       [[2., 6.],
        [2., 6.],
        [2., 6.]],

       [[3., 7.],
        [3., 7.],
        [3., 7.]],

       [[4., 8.],
        [4., 8.],
        [4., 8.]]])

Which is almost what you want, except for the extra dimension. So now you can just reshape this and get your (12, 2) array the way you want:

In : x.T.reshape((-1, 2))
Out: 
array([[1., 5.],
       [1., 5.],
       [1., 5.],
       [2., 6.],
       [2., 6.],
       [2., 6.],
       [3., 7.],
       [3., 7.],
       [3., 7.],
       [4., 8.],
       [4., 8.],
       [4., 8.]])

Comments

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.