Search code examples
pythonnumpyindexinginsert

Insert element at nth position in Array with numpy.insert


I try to insert np.nan values into an array at the nth position. Desired output:

array(['1', 'nan', 'nan', '2', test', '3'])

I tried with this code:

position = [1,2]
array= np.array([1,2,'test', 3])
array= np.insert(array, position, np.nan)

But it is inserting the values at index 1 and 3:

array(['1', 'nan', '2', 'nan', 'test', '3'])

How can I fix this?


Solution

  • Inserting would take place altogether for both np.nan. So, if you use [1,2] then index 1 would be between 1 and 2, and index 2 would be between 2 and 'test'. The position needs to be [1,1] if you want to insert continuous values.

    import numpy as np
    
    position = [1,1]
    array = np.array([1,2,'test', 3])
    array = np.insert(array, position, np.nan)
    print(array)
    

    Output:

    ['1' 'nan' 'nan' '2' 'test' '3']