0

Suppose I have an array of arrays.

import numpy as np
x = np.array([ [1, 2], [3, 4], [5, 6]])

I want to add 10 as the first element of each of those arrays without running for loop. Result should look like

array([[10, 1, 2],
       [10, 3, 4],
       [10, 5, 6]])

Plain append does not work.

np.append(10, x)
array([10,  1,  2,  3,  4,  5,  6])

My original problem has 100K arrays. So I need to find an efficient way to do this.

1
  • That is not an array of arrays. Commented Apr 9, 2021 at 3:17

2 Answers 2

1

You are looking for np.insert. https://numpy.org/doc/stable/reference/generated/numpy.insert.html

np.insert(x, 0, [10,10,10], axis=1)

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

Comments

1

np.insert is your choice

>>> import numpy as np
x = np.array([ [1, 2], [3, 4], [5, 6]])

>>> x
array([[1, 2],
       [3, 4],
       [5, 6]])

>>> np.insert(x, 0, 10, axis=1)

array([[10,  1,  2],
       [10,  3,  4],
       [10,  5,  6]])

you also can insert different values

>>> np.insert(x, 0, [10,11,12] , axis=1)

array([[10,  1,  2],
       [11,  3,  4],
       [12,  5,  6]])

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.