I am trying to replace part of my array (let's say 10% of length of a given array) with NaNs. I know that if I wanted to replace only particular values (e.g. bigger than 255), I can do it using arr[arr > 255] = np.NaN. But what if I want the replaced values to be selected randomly?
Add a comment
|
1 Answer
Is this what you trying:
import numpy as np
import random
an_array = np.array([5, 6, 7,2,4,5,6,7,8,9])
an_array = an_array.astype("float")
percent_len = round(len(an_array) * 10 / 100)
print(f'percent len : {percent_len}')
index_visited = []
print('Before:')
print(an_array)
for i in range(percent_len):
while True:
some_index = random.randint(0,percent_len)
if some_index in index_visited:
continue
else:
index_visited.append(some_index)
break
an_array[some_index] = np.nan
print()
print('After:')
print(an_array)
result:
