'Stack the same row in each layer of a 3D numpy array

Hi is there a way to efficiently stack the same row in each layer of a 3D numpy array? I have an array like this:

 a = np.array([[["a111","a112","a113"],
                ["b","b","b"],
                ["c","c","c"],
                ["d","d","d"]],
               [["a211","a212","a213"],
                ["b","b","b"],
                ["c","c","c"],
                ["d","d","d"]],
              [["a311","a312","a313"],
                ["b","b","b"],
                ["c","c","c"],
                ["d","d","d"]],
             [["a411","a412","a413"],
                ["b","b","b"],
                ["c","c","c"],
                ["d","d","d"]]])

and i want to get something like this:

np.array([[["a111","a112","a113"],
                ["a211","a212","a213"],
                ["a311","a312","a313"],
                ["a411","a412","a413"]],
               [["b","b","b"],
                ["b","b","b"],
                ["b","b","b"],
                ["b","b","b"]],
               [["c","c","c"],
                ["c","c","c"],
                ["c","c","c"],
                ["c","c","c"]],
               [["d","d","d"],
                ["d","d","d"],
                ["d","d","d"],
                ["d","d","d"]]])

Right now I'm looping through the whole array and stacking it manually.



Solution 1:[1]

Use swapaxes:

a.swapaxes(0,1)

output:

array([[['a111', 'a112', 'a113'],
        ['a211', 'a212', 'a213'],
        ['a311', 'a312', 'a313'],
        ['a411', 'a412', 'a413']],

       [['b', 'b', 'b'],
        ['b', 'b', 'b'],
        ['b', 'b', 'b'],
        ['b', 'b', 'b']],

       [['c', 'c', 'c'],
        ['c', 'c', 'c'],
        ['c', 'c', 'c'],
        ['c', 'c', 'c']],

       [['d', 'd', 'd'],
        ['d', 'd', 'd'],
        ['d', 'd', 'd'],
        ['d', 'd', 'd']]], dtype='<U4')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway