Reputation: 469
I'm trying to figure out how to append an empty list to an already existing numpy array
can I get an array for any list b
a = np.array([b])
a = np.append(a, [])
print a # you get array([a, []])
this code just outputs the original [a] instead of [a, []]. Does anyone know how this is achieved?
Upvotes: 0
Views: 769
Reputation: 231665
The only way you can have an empty list in array is to make an object dtype array.
In [382]: a = np.empty((3,),dtype=object)
In [383]: a
Out[383]: array([None, None, None], dtype=object)
In [384]: a[0]=[1,2,3]
In [385]: a[1]=[]
In [386]: a
Out[386]: array([[1, 2, 3], [], None], dtype=object)
or from a list of lists (of varying length)
In [393]: np.array([[1,2,3],[]])
Out[393]: array([[1, 2, 3], []], dtype=object)
You can concatenate one object array to another:
In [394]: a = np.empty((1,),object); a[0]=[1,2,3]
In [395]: a
Out[395]: array([[1, 2, 3]], dtype=object)
In [396]: b = np.empty((1,),object); b[0]=[]
In [397]: b
Out[397]: array([[]], dtype=object)
In [398]: np.concatenate((a,b))
Out[398]: array([[1, 2, 3], []], dtype=object)
np.append
wraps concatenate
, and is designed to add a scalar to another array. What it does with a list, empty or otherwise, is unpredictable.
I take that last comment back; np.append
turns the list into a simple array. These all do the same thing
In [413]: alist=[1,2]
In [414]: np.append(a,alist)
Out[414]: array([[1, 2, 3], 1, 2], dtype=object)
In [415]: np.concatenate((a, np.ravel(alist)))
Out[415]: array([[1, 2, 3], 1, 2], dtype=object)
In [416]: np.concatenate((a, np.array(alist)))
Out[416]: array([[1, 2, 3], 1, 2], dtype=object)
Upvotes: 1