Zygro
Zygro

Reputation: 7119

Numpy 3d array to 2d array by outermost index

I have an array of 2d arrays like

+------+    +------+
|      |    |      |
|  A   |    |  B   |
|      |    |      |
+------+    +------+

and I want to "delete" the outermost parentheses, as in to get

+------+------+
|      |      |
|  A   |  B   |
|      |      |
+------+------+

for example I have

[[[1,1,1],[2,2,2]],[[3,3,3],[4,4,4]]]

and I want to get

[[1,1,1,3,3,3],[2,2,2,4,4,4]]

in other words, I need to make an array of shape (7,3,1000) into (3,7000) by appending those 7 in chain

how to go about it?

Upvotes: 1

Views: 37

Answers (1)

Divakar
Divakar

Reputation: 221514

One approach with swapping of axes between first and second ones and then reshape to merge the last two axes -

arr.swapaxes(0,1).reshape(arr.shape[1],-1)

Sample run -

In [9]: arr = np.array([[[1,1,1],[2,2,2]],[[3,3,3],[4,4,4]]])

In [10]: arr.swapaxes(0,1).reshape(arr.shape[1],-1)
Out[10]: 
array([[1, 1, 1, 3, 3, 3],
       [2, 2, 2, 4, 4, 4]])

Upvotes: 2

Related Questions