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?

Anonymous
  • 295
  • 2
  • 13
  • 1
    Perhaps https://stackoverflow.com/questions/33983053/how-to-create-a-numpy-array-of-lists – IronMan Aug 05 '19 at 18:29
  • 2
    Why do you need such a structure? – Paritosh Singh Aug 05 '19 at 18:48
  • It is _very likely_ that you _do not want_ a numpy array of lists. – rafaelc Aug 05 '19 at 20:10
  • `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). – hpaulj Aug 05 '19 at 20:17

1 Answers1

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.

hilberts_drinking_problem
  • 11,322
  • 3
  • 22
  • 51
  • 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`. – hpaulj Aug 05 '19 at 20:22