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?
CodePudding user response:
The position should be [1, 1]. Position 2 is between 2 and 'test' and 1 is between 1 and 2. The index where you insert them is where the index is located in the initial array, not where they will end up.
CodePudding user response:
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']
CodePudding user response:
The numpy.insert() function inserts values before the given indices.
i.e. for the given array :
[1, 2,'test',3]
0 1 2 3 -> index
Inserting at position=[1,2] will insert values before index 1 (value =2) and before index 2(value ='test') in the original array i.e.
[1, ___, 2, ___, 'test',3]
In order to get both nan inserted before index 1, write as
import numpy as np
position = [1,1]
array= np.array([1,2,'test', 3])
array= np.insert(array, position, np.nan)
print(array)
You will get the desired result:
['1' 'nan' 'nan' '2' 'test' '3']
Note: This position array is not the index of the new values you want to insert, it is the index before which you want to insert the new values