Skip to content Skip to sidebar Skip to footer

Numpy Array Of Numpy Arrays

When I create a numy array of a list of sublists of equal length, it implicitly converts it to a (len(list), len(sub_list)) 2d array: >>> np.array([[1,2], [1,2]],dtype=obj

Solution 1:

Here you go...create with dtype=np.ndarray instead of dtype=object.

Simple example below (with 5 elements):

In [1]: arr = np.empty((5,), dtype=np.ndarray)
In [2]: arr.shape
Out[2]: (5,)
    
In [3]: arr[0]=np.array([1,2])
In [4]: arr[1]=np.array([2,3])
In [5]: arr[2]=np.array([1,2,3,4])
In [6]: arr
Out[6]: 
array([array([1, 2]), array([2, 3]), array([1, 2, 3, 4]), None, None],
      dtype=object)

Solution 2:

You can create an array of objects of the desired size, and then set the elements like so:

elements = [np.array([1,2]), np.array([1,2])]

arr = np.empty(len(elements), dtype='object')
arr[:] = elements

But if you try to cast to an array directly with a list of arrays/lists of the same length, numpy will implicitly convert it into a multidimensional array.

Solution 3:

np.array([[1,2], [1,2]],dtype=object)[0].shape

Post a Comment for "Numpy Array Of Numpy Arrays"