Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split NumPy array with dimensionality reduction?

This script:

import numpy as np

a = np.arange(8).reshape(2, 2, 2)
b = np.split(a, 2)
print(b[0].shape)

produces:

(1, 2, 2)

I would like to split array a into a list of constituent subarrays with shape (2, 2), reducing their dimension in the process. Instead, I'm getting a list of subarrays of (1, 2, 2) shape. Is there a way to get what I want without removing the extra dimension in an additional step?

like image 747
Paul Jurczak Avatar asked Jul 26 '26 02:07

Paul Jurczak


1 Answers

I check now via my code iterating over a unpacks along axis 0 and each x has shape(2, 2)

import numpy as np

a = np.arange(8).reshape(2, 2, 2)
b = [x for x in a]
print(b[0].shape)

One other way is

import numpy as np

a = np.arange(8).reshape(2, 2, 2)
b = list(a)
print(b[0].shape)

for one line code:

import numpy as np

a = list(np.arange(8).reshape(2, 2, 2))[0].shape
print(a)
like image 158
Kashif Avatar answered Jul 27 '26 15:07

Kashif