konstantin
konstantin

Reputation: 893

Replace randomly an index from numpy vector

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?

Upvotes: 1

Views: 44

Answers (1)

akuiper
akuiper

Reputation: 215137

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.]])

Upvotes: 2

Related Questions