Hi I would like to change all the values in this array (test) simultaneously based on a second boolean array (test_map) without iterating over each item.
test = np.array([1,1,1,1,1,1,1,1])
test_map = np.array([True,False,False,False,False,False,False,True])
test[test_map] = random.randint(0,1)
output:
array([0, 1, 1, 1, 1, 1, 1, 0]) or array([1, 1, 1, 1, 1, 1, 1, 1])
The problem with this is that I want the values that should be changed (in this case the first and last value) to each randomly be changed to a 0 or 1. So the 4 possible outputs should be:
array([0, 1, 1, 1, 1, 1, 1, 0]) or array([1, 1, 1, 1, 1, 1, 1, 1]) or array([1, 1, 1, 1, 1, 1, 1, 0]) or array([0, 1, 1, 1, 1, 1, 1, 1])
CodePudding user response:
One possible solution is to generate a random array of "bits", with np.random.randint
:
import numpy as np
test = np.array([1,1,1,1,1,1,1,1])
test_map = np.array([True,False,False,False,False,False,False,True])
# array of random 1/0 of the same length as test
r = np.random.randint(0, 2, len(test))
test[test_map] = r[test_map]
test
CodePudding user response:
You can generate just as many random integers as you need by passing the number of True
values in test_map
as the size
argument to np.random.randint()
:
test[test_map] = np.random.randint(0, 2, size=np.sum(test_map))