0

Say I have two unique arrays:

a = [1,20,21, 67,4, 20, 90, 54,90, 78]
b= [3, 654, 342, 309, 245, 213, 984, 56, 89, 23]

If I pass the value "20%", I want to randomly replace 20% of the values in array a with the values in the array b for the same indices.

Output:

a = [3, 20, 21, 67, 4, 20, 90, 54, 90, 23] 

Here is what I have tried:

a = [1,20,21, 67,4, 20, 90, 54,90, 78]
b= [3, 654, 342, 309, 245, 213, 984, 56, 89, 23]
percentage = 0.2
no_of_replaced_values = int(len(a)*percentage)
sl = slice(0, no_of_replaced_values)
a[0:no_of_replaced_values]=b[sl]
print(a)

This gives an output of a= [3, 654, 21, 67, 4, 20, 90, 54, 90, 78]. Instead of consecutive values being changed, I want to randomly change them.

Marcelo Paco
  • 2,732
  • 4
  • 9
  • 26

1 Answers1

1

use random.sample which gives can be used to give n random indices from a list. Then replace the elements at the random indices.

random.sample(range(0, len(a)), n)
# range(0, len(a)) -> list of indices of a [0, 1, 2 ... len(a)-1]
# n                -> number of elements from list
import random
a = [0, 0, 0, 0, 0, 0, 0, 0]
b = [1, 1, 1, 1, 1, 1, 1, 1]

def func(a, b, percentage):
    n = int(len(a)*percentage)
    inds = random.sample(range(0, len(a)), n)
    for i in inds:
        a[i] = b[i]
    return a

print(func(a[:], b[:], 0.20))
print(func(a[:], b[:], 0.20))
print(func(a[:], b[:], 0.50))

Result:

[0, 1, 0, 0, 0, 0, 0, 0]     # (20%) replaced 1 random element
[0, 0, 0, 0, 1, 0, 0, 0]     # (20%)
[1, 0, 1, 0, 0, 1, 1, 0]     # (50%) replace half the elements
Yash
  • 391
  • 3
  • 14