Chris J Harris
Chris J Harris

Reputation: 1851

Reshaping a three-dimensional ndarray into two dimensions

I have a three-dimensional array (shape is 2,2,3), which can be thought of as a combination of two two-dimensional arrays. I'd like to get these two arrays and put them side-by-side. Here's my starting point:

test1 = np.ndarray((2,2,3))
test1[0] = np.array([[1,2,3],
                     [4,5,6]])
test1[1] = np.array([[7,8,9],
                     [10,11,12]])

I can get to the desired result by iterating through the first dimension, likeso:

output = np.ndarray((2,6))
for n_port, port in enumerate(test1):
    output[:,n_port*3:(n_port+1)*3] = port  

which gives:

array([[ 1.,  2.,  3.,  7.,  8.,  9.],
       [ 4.,  5.,  6., 10., 11., 12.]])

But I'm wondering if there's a slicker way to do it. The reshape function would be the obvious way to go but it flattens them out, rather than stacking them side-by-side:

test1.reshape((2,6))
array([[ 1.,  2.,  3.,  4.,  5.,  6.],
       [ 7.,  8.,  9., 10., 11., 12.]])

Any help gratefully received!

Upvotes: 1

Views: 679

Answers (2)

kmario23
kmario23

Reputation: 61355

Based on the backtracking idea described in the thread: intuition and idea behind reshaping 4D array to 2D array in numpy, you can use a combination of arr.transpose and arr.reshape as in:

In [162]: dd = np.arange(1, 13).reshape(2, 2, 3)

In [163]: dd
Out[163]: 
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])

In [164]: dd.transpose((1, 0, 2))
Out[164]: 
array([[[ 1,  2,  3],
        [ 7,  8,  9]],

       [[ 4,  5,  6],
        [10, 11, 12]]])

In [165]: dd.transpose((1, 0, 2)).reshape(2, -1)
Out[165]: 
array([[ 1,  2,  3,  7,  8,  9],
       [ 4,  5,  6, 10, 11, 12]])

Upvotes: 2

llllllllll
llllllllll

Reputation: 16404

You can do a swapaxes() first, then reshape():

test1.swapaxes(0,1).reshape(2,6)

Upvotes: 1

Related Questions