Building an array in python

Suppose we have an array of length 1000

, where are all its values 1

, that is, this is how [1,1,1,1,1,1,…,1,1,1,1]

. Now suppose that we want to convert this array into an array of blocks so that the 25%

array was a unit 0

instead 1

arranged uniformly at random positions . Hence the final array would be something like [1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,…,1,1,1,0,0,0]

.

Is there an efficient way for python / numpy?

+3


source to share


1 answer


You can create a list of random indices with the length of the main list 0.25

and then change that the indices in the main list are 0.

>>> l=np.ones(30)
>>> length=len(l)
>>> rand=np.arange(int(0.25*length))
>>> np.random.shuffle(rand)
>>> l[rand]=0
>>> l
array([0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,
       0, 0, 1, 1, 1, 0, 1])

      



And more precisely, you can do:

main_list[np.random.choice(length,int(0.25*length),replace=False)]=0

      

+1


source







All Articles