1

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?

1
  • Are you really starting with a numpy array? Note that while your array definition has a mix of numbers and str, the result is string dtype. And the np.nan is inserted as a string. In a comment you talk about replacing 'string types' with nan in a dataset. That sounds more like a pandas operation. Remember np.nan is a float. Do you want to mix integers, floats, and strings? Commented Apr 23, 2022 at 16:44

3 Answers 3

2

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']
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.