1

I want to create a method that will receive a numpy vector of size 1xN which contain several values among them several NaN too and will randomly replace a non-nan index with NaN. I want the return the result and also the index of the replaced element.

def replace_index(array):
   index = np.random.randint(array.shape[1], size=1)
   array[index] = NaN
   return array, index

How can i check if the calculated index is not already a nan?

1 Answer 1

2

You can use numpy.where and numpy.isnan to locate the indices where values are not nan, then use np.random.choice to pick one index that is not nan:

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

not_nan_idx = np.random.choice(np.where(~np.isnan(array))[1])

not_nan_idx
# 2

array[0, not_nan_idx] = np.nan

array
# array([[ 1., nan, nan, nan,  3.,  4.]])
Sign up to request clarification or add additional context in comments.

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.