0

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?

1 Answer 1

1

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:

enter image description here

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.