Navid777
Navid777

Reputation: 3681

numpy insert an element keeping number of array dimensions

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

Answers (2)

RomanPerekhrest
RomanPerekhrest

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

akuiper
akuiper

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

Related Questions