Home > Net >  Is there a function I can use in Python to randomly select elements equal to specified number and ch
Is there a function I can use in Python to randomly select elements equal to specified number and ch

Time:04-16

For instance, if I have the following distribution, I want to randomly select 4 elements = 1 and change that element to = 0.

lst = [1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0]

-> Function <-

lst = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0]

or

lst = [1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]

or

lst = [0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0]

or ....

CodePudding user response:

Using numpy:

ones = np.where(lst)[0]
to_zero = np.random.choice(ones, 4, replace=False)
for i in to_zero: # Alternatively, if lst is an array: lst[to_zero] = 0
  lst[i] = 0

CodePudding user response:

To achieve what you want, you first need to get the list of the indexes of the one elements. Then you need to pick 4 random indexes and update the values from the starting list.
Note that you cannot use the random.choices method because it doesn’t return unique values, use random.sample instead.

def update_randomly(tab):
    n = range(len(tab))
    one_indexes = [i for i in n if tab[i] == 1]
    rdm_indexes = random.sample(one_indexes, 4)
    return [0 if i in rdm_indexes else tab[i] for i in n]
  • Related