How to initialize Numpy array of list objects
Asked Answered
G

1

6

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?

German answered 5/8, 2019 at 18:26 Comment(4)
Perhaps #33983553Lacewing
Why do you need such a structure?Zulazulch
It is very likely that you do not want a numpy array of lists.Marlo
np.array tries to create multidimensional numeric (or string) array, which it can do if all the input lists have a consistent size. It's only when the sizes differ that it falls back on creating an object dtype array (or in some cases raising an error).Moll
I
9

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.

Ileenileitis answered 5/8, 2019 at 18:48 Comment(1)
I've recommended frompyfunc as a way of filling an array with custom class instances. This is a nice use of the idea with standard types like list.Moll

© 2022 - 2024 — McMap. All rights reserved.