Reputation: 1135
I want to generate a numpy array filled empty lists. I tried this:
import numpy as np
arr=np.full(6, fill_value=[], dtype=object)
And I got an error:
ValueError: could not broadcast input array from shape (0) into shape (6)
But if I use:
arr = np.empty(6, dtype=object)
arr.fill([])
It is ok. Why does numpy.full
not work here? What is the right way to initialize an array filled with empty lists?
Upvotes: 2
Views: 1596
Reputation: 35560
The reason you can't use fill_value=[]
is hidden in the docs:
In the docs, it says that np.full
's fill_value
argument is either a scalar or array-like. In the docs for np.asarray
, you can find their definition of array-like:
Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.
So, lists are treated specially as "array" fill types and not scalars, which is not what you want. Additionally, arr.fill([])
is actually not what you want, since it fills every element to the same list, which means appending to one appends to all of them. To circumvent this, you can do that this answer states, and just initialize the array with a list:
arr = np.empty(6, dtype=object)
arr[...] = [[] for _ in range(arr.shape[0])]
which will create an array with 6 unique lists, such that appending to one does not append to all of them.
Upvotes: 4
Reputation: 71
You can try to use numpy.empty(shape, dtype=float, order='C')
Upvotes: -1