How to split NumPy array with dimensionality reduction?

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 constituent subarrays with shape (2, 2), reducing their dimension in the process. Instead, I'm getting subarrays of (1, 2, 2) shape. Is there a way to get what I want without removing the extra dimension in additional step?

Answer

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)

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions