pythonnumpy

Reshape 4D array to 2D


I have the array

import numpy as np

a1 = [["a1", "a2"],
      ["a3", "a4"],
      ["a5", "a6"],
      ["a7", "a8"]]

b1 = [["b1", "b2"],
      ["b3", "b4"],
      ["b5", "b6"],
      ["b7","b8"]]

c1 = [["c1", "c2"],
      ["c3", "c4"],
      ["c5", "c6"],
      ["c7","c8"]]

arr = np.array([a1, b1, c1])
#arr.shape
#(3, 4, 2)

Which I want to reshape to a 2D array:

["a1","b1","c1"],
["a2","b2","c2"],
...,
["a8","b8","c8"]

I've tried different things like:

# arr.reshape((8,3))
# array([['a1', 'a2', 'a3'],
#        ['a4', 'a5', 'a6'],
#        ['a7', 'a8', 'b1'],
#        ['b2', 'b3', 'b4'],
#        ['b5', 'b6', 'b7'],
#        ['b8', 'c1', 'c2'],
#        ['c3', 'c4', 'c5'],
#        ['c6', 'c7', 'c8']])

#arr.T.reshape(8,3)
# array([['a1', 'b1', 'c1'],
#        ['a3', 'b3', 'c3'],
#        ['a5', 'b5', 'c5'],
#        ['a7', 'b7', 'c7'],
#        ['a2', 'b2', 'c2'],
#        ['a4', 'b4', 'c4'],
#        ['a6', 'b6', 'c6'],
#        ['a8', 'b8', 'c8']]

# arr.ravel().reshape(8,3)
# array([['a1', 'a2', 'a3'],
#        ['a4', 'a5', 'a6'],
#        ['a7', 'a8', 'b1'],
#        ['b2', 'b3', 'b4'],
#        ['b5', 'b6', 'b7'],
#        ['b8', 'c1', 'c2'],
#        ['c3', 'c4', 'c5'],
#        ['c6', 'c7', 'c8']])

Solution

  • What you want is to stack the arrays such that the final 2D shape is (8, 3), where each row contains the same index from each original array.

    So the key is to use np.array(arr).transpose(1, 2, 0).reshape(-1, 3).

    Code Example:

    import numpy as np
    
    a1 = [["a1", "a2"],
         ["a3", "a4"],
         ["a5", "a6"],
         ["a7", "a8"]]
    b1 = [["b1", "b2"],
         ["b3", "b4"],
         ["b5", "b6"],
         ["b7","b8"]]
    c1 = [["c1", "c2"],
         ["c3", "c4"],
         ["c5", "c6"],
         ["c7","c8"]]
    
    arr = np.array([a1, b1, c1])  # shape: (3, 4, 2)
    
    result = arr.transpose(1, 2, 0).reshape(-1, 3)
    
    print(result)