jhp jhp - 1 month ago 4x
Python Question

How to create a numpy _object_ array of other numpy arrays of same and different length?

This is my very first question. So let's see if I can explain exactly what I need.

I am given a python

of numpy arrays which can or cannot have different lengths (in one dimension only but this is not important here), e.g.

my_list = [
np.ones((20, 3, 3)),
np.ones(( 1, 3, 3)),
np.ones((20, 3, 3))

Now when I do

wrapped_list = np.array(my_list)

I get an object of the following structure

np.array(shape=(3, ), dtype=object)

with the initial three arrays as content. This is what I want. Now the problem:

contained sublists of identical length, then I get, e.g.

my_list2 = [
np.ones((20, 3, 3)),
np.ones((20, 3, 3)),
np.ones((20, 3, 3))


leads to

np.array(shape=(3, 20, 3, 3), dtype=np.float64)

This is not, what I want. I tried specifying the
, like

np.array(my_list, dtype=object)

which will cast all (sub-)arrays to

I think I found a way to go without wrapping at all, but I am curious on how to set the dtype on a np.array without affecting nested numpy arrays.


Create an empty object arrary first and fill it with my_list, e.g.:

wrapped_list = np.empty((3,),dtype=object)
wrapped_list[:] = my_list2