2
$\begingroup$

I have 100 2D lists a0 to a99, it is easy to convert them into arrays (I verified already):

print(np.array(a0).shape)   # (2,150)
print(np.array(a1).shape)   # (5,150)
print(np.array(a2).shape)   # (10, 150)
# the sizes of a0 to a99 vary from (1,150) to (10, 150) only

I want to combine these 100 3D arrays into ONE 3D array, for example combined_array:

print(combined_array.shape)  # (100,10,150)
print(combined_array[0].shape) # (2,150)
print(conbined_array[1].shape) # (5,150)
print(combined_array[2].shape) # (10,150)

I use Python 3.7.

$\endgroup$
1
$\begingroup$

Your arrays have different shapes on the 0 axis, so you cannot use numpy.stack directly.

You can either use padding or put all arrays in a list. Using padding:

import numpy as np

a0 = np.empty((2,150))
a1 = np.empty((5,150))
a2 = np.empty((10,150))

max_shape = [0,0]
for a in [a0, a1, a2]:
    if max_shape[0] < a.shape[0]:
        max_shape[0] = a.shape[0]
    if max_shape[1] < a.shape[1]:
        max_shape[1] = a.shape[1]
arrays = []
for a in [a0, a1, a2]:
    arrays.append(np.pad(a, pad_width=((0, max_shape[0] - a.shape[0]),
                                       (0, max_shape[1] - a.shape[1])),
                         mode='constant'))
stacked_array = np.stack(arrays)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.