'Is there a function I can use in Python to randomly select elements equal to specified number and change it to another?
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 ....
Solution 1:[1]
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
Solution 2:[2]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mxbi |
| Solution 2 | Lukas Laudrain |
