'Inserting a new entry into a 1 dimensional numpy array without distrubing other entries [duplicate]

Consider the following: If I have a 1 dimensional array like the following

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

Say now that I have the number 3, and wish to enter it into the 3rd position of the array (or 2nd position in "python language") without distrubing other entries so that we once we call array again after the function, we obtain:

x=np.array([1,2,3,4,5])

I'm looking for some kind of, for a lack of a better word, "splicing method" involving the array x and the number 3.

Thank you!



Solution 1:[1]

You can use numpy.insert

numpy.insert(arr, obj, values, axis=None)

arr -> array you want your value/values inserted to

obj -> could be an integer, a slice or a sequence of values

values -> as you can imagine, the value/values you want to insert

axis -> it works also for multi-dimensional array

Here's the solved example that you have proposed:

import numpy as np

idx = 2
val = 3

x = np.array([1,2,4,5])
x = np.insert(x,idx,val,axis=0)

Here's the result

pre-insert : [1 2 4 5]
post-insert : [1 2 3 4 5]

As you can see, this method will put in the position idx=2 of the array x in the value val=3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Luca Villani