3

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.