Is there any way to insert a tuple into numpy array? Let's say I have:
[1,2,3,4,5,6]
But what I want is:
[1,2,3,(4,5,6)]
CodePudding user response:
You can use append()
a = [1,2,3]
a.append((4,5,6))
Some documentations you may find useful
CodePudding user response:
Nico is right - list append can create the object you show:
In [155]: alist = [1,2,3]
In [156]: alist.append((4,5,6))
In [157]: alist
Out[157]: [1, 2, 3, (4, 5, 6)]
You misread Nico, and tried np.append
. It is not a list append clone!
First look at this array:
In [165]: arr = np.array([1,2,3])
In [166]: arr
Out[166]: array([1, 2, 3])
In [167]: print(arr)
[1 2 3]
It doesn't display as a list. It is not a list, and cannot hold a tuple. It can only hold integers (check the dtype
).
np.append
clearly says that it flattens all inputs:
In [168]: arr1 = np.append(arr,(4,5,6))
In [169]: arr1
Out[169]: array([1, 2, 3, 4, 5, 6])
A clearer way to express this
In [170]: np.hstack((arr, np.array([4,5,6])))
Out[170]: array([1, 2, 3, 4, 5, 6])
As for speed - list append is the best way to go if you are building lists in a loop. Copying list methods with arrays is a bad idea.