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