MNayer
MNayer

Reputation: 181

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=object).shape
(2, 2)

But when I pass variable length sublists it creates a vector of length len(list):

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

How can I get a vector output when the sublists are the same length (i.e. make the first case behave like the second)?

Upvotes: 0

Views: 1281

Answers (3)

Newcomer
Newcomer

Reputation: 73

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

Upvotes: 0

iacob
iacob

Reputation: 24161

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.

Upvotes: 1

kcw78
kcw78

Reputation: 7996

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)

Upvotes: 2

Related Questions