Append an Element to Array of Arrays

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

2 Answers

You are looking for np.insert.

np.insert(x, 0, [10,10,10], axis=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]])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest