How can I convert a 3D numpy array into sub-dimension arrays? For example, I have a 3D numpy array of shape(100,3,3) and I want to convert it into a vector of 100 2D arrays of shape (3,3)?
Asked
Active
Viewed 1,892 times
-5
-
5Trying to get the bigger picture - Why do you need that? – Divakar Jun 01 '17 at 11:08
-
just in case what you're trying to do is import cells into matlab / octave: https://stackoverflow.com/questions/38960464/using-scipy-io-savemat-to-save-nested-lists/38961751#38961751 – Tasos Papastylianou Jun 01 '17 at 11:39
-
As @Divakar mentioned, why would you need that? A 3d array it is by definition a 1d of 2d :S You can do same slicing operations to a 3d numpy array than to a list of 2d arrays. – Imanol Luengo Jun 01 '17 at 11:53
-
the point is i want to join several arrays(diffent dimensions)in one 2d array, i tried with column_stack() but didnt' work. – mohamed zaki Jun 01 '17 at 12:27
2 Answers
6
For doing this, use the numpy.split
function. Assuming you have
my_array = np.zeros((100, 3, 3))
use:
my_new_array = np.split(my_array, 100, axis=0).
From this you will get an array containing 100 arrays with shape (1,3,3). If you like to get a list with the (3,3) arrays, just use a list comprehension:
my_list = [my_array[i] for i in range(np.shape(my_array)[0])]
.

Franz
- 623
- 8
- 14
-
2
-
-
-
my_array already is an array of arrays. You can slice it directly by `my_array[4]` for example – Franz Jun 01 '17 at 12:26
0
As per this answer which needed this in order for the individual 3x3 arrays to become cell elements in savemat:
import numpy
A = numpy.zeros((100,3,3))
B = numpy.empty((100,), dtype=numpy.object)
for i in range(100): B[i] = A[i,:,:]

Tasos Papastylianou
- 21,371
- 2
- 28
- 57