'Add list to numpy array
I have an initial array that looks like that:
[[2, 3, 0], [4, 5, 0], [4, 0], [5, 0], [3, 0]]
after I use np.asarray(arr, dtype = object) it becomes like that:
[list([2, 3, 0]) list([4, 5, 0]) list([4, 0]) list([5, 0]) list([3, 0])]
and the problem is that I cant add another list because after adding one with np.append(arr, list([0]) its look like that:
[list([2, 3, 0]) list([4, 5, 0]) list([4, 0]) list([5, 0]) list([3, 0]) 0]
instead of
[list([2, 3, 0]) list([4, 5, 0]) list([4, 0]) list([5, 0]) list([3, 0]) list([0])]
and if I add more, for example with np.append(arr, list([1,2,3,0]) they are just added to the end as a simple number.
So the question is how I could add a list to the NumPy array that I could use with arr[i] to print the entire list?
Solution 1:[1]
np.append automatically flattens the list you pass it, unless you're append one array to another rectangular array. From the docs (emphasis mine):
axis:int, optional The axis along whichvaluesare appended. Ifaxisis not given, botharrandvaluesare flattened before use.
In your case, I'd convert the array to a list, add the item, then convert it back to an array:
>>> a
array([list([2, 3, 0]), list([4, 5, 0]), list([4, 0]), list([5, 0]), list([3, 0])], dtype=object)
>>> np.array(a.tolist() + [[0,1,2,3]])
array([list([2, 3, 0]), list([4, 5, 0]), list([4, 0]), list([5, 0]), list([3, 0]), list([0, 1, 2, 3])], dtype=object)
Solution 2:[2]
With lists it's easy to add a list:
In [41]: alist =[[2, 3, 0], [4, 5, 0], [4, 0], [5, 0], [3, 0]]
In [42]: alist.append([0])
In [43]: alist
Out[43]: [[2, 3, 0], [4, 5, 0], [4, 0], [5, 0], [3, 0], [0]]
In [53]: arr = np.array(alist,object)
In [54]: arr
Out[54]:
array([list([2, 3, 0]), list([4, 5, 0]), list([4, 0]), list([5, 0]),
list([3, 0]), list([0])], dtype=object)
To do something similar with arrays, we have to first construct an object dtype array containing the desired list:
In [55]: toadd = np.array([None]); toadd[0] = [0]
In [56]: toadd
Out[56]: array([list([0])], dtype=object)
In [57]: np.concatenate((arr, toadd))
Out[57]:
array([list([2, 3, 0]), list([4, 5, 0]), list([4, 0]), list([5, 0]),
list([3, 0]), list([0]), list([0])], dtype=object)
The concatenate combines a (5,) array with a (1,). The number of dimensions have to match.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | hpaulj |
