Reputation: 3681
I have a numpy array like this:
[[1, 2, 3], [1, 2, 4]]
and I want to append an element [100, 101, 102]
to the array like this:
[[1, 2, 3], [1, 2, 4], [100, 101, 102]]
I tried numpy.append
but it creates a 1D array with all the elements. How can I do that?
Upvotes: 3
Views: 934
Reputation: 92894
Or with np.vstack(tup) routine:
import numpy as np
arr = np.array([[1, 2, 3], [1, 2, 4]])
arr = np.vstack((arr, [100, 101, 102]))
print(arr)
The output:
[[ 1 2 3]
[ 1 2 4]
[100 101 102]]
Upvotes: 2
Reputation: 215117
You need to specify axis
when using np.append
and also the value needs to have the correct shape; The following works:
a = [[1, 2, 3], [1, 2, 4]]
b = [100, 101, 102]
np.append(a, [b], axis=0)
#array([[ 1, 2, 3],
# [ 1, 2, 4],
# [100, 101, 102]])
If you have lists:
a.append(b)
np.array(a)
Should be more efficient.
Upvotes: 3