Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize Numpy array of list objects

I'm trying to create a numpy array that looks like

array([[list([]), list([])],
       [list([]), list([])],
       [list([]), list([])]], dtype=object)

This array has shape (3,2). However, whenever I do

np.array([[list(), list()], [list(), list()], [list(), list()]])

I end up getting

array([], shape=(3, 2, 0), dtype=float64)

How do I solve this?

like image 568
Anonymous Avatar asked Aug 05 '19 18:08

Anonymous


People also ask

Can you make a NumPy array of lists?

We can use numpy ndarray tolist() function to convert the array to a list. If the array is multi-dimensional, a nested list is returned. For one-dimensional array, a list with the array elements is returned.

Can you create a NumPy array of objects?

The array object in NumPy is called ndarray . We can create a NumPy ndarray object by using the array() function.


1 Answers

You could use the following:

np.frompyfunc(list, 0, 1)(np.empty((3,2), dtype=object))  

We first turn list into a ufunc that takes no arguments and returns a single empty list, then apply it to an empty 3x2 array of object type.

like image 165
hilberts_drinking_problem Avatar answered Oct 12 '22 02:10

hilberts_drinking_problem