How to randomly set elements in numpy array to 0

后端 未结 4 2190
我在风中等你
我在风中等你 2021-02-19 06:33

First I create my array

myarray = np.random.random_integers(0,10, size=20)

Then, I want to set 20% of the elements in the array to 0 (or some o

4条回答
  •  半阙折子戏
    2021-02-19 06:53

    If you want the 20% to be random:

    random_list = []
    array_len = len(myarray)
    
    while len(random_list) < (array_len/5):
        random_int = math.randint(0,array_len)
        if random_int not in random_list:
            random_list.append(random_int)
    
    for position in random_list:
        myarray[position] = 0
    
    return myarray
    

    This would ensure you definitely get 20% of the values, and RNG rolling the same number many times would not result in less than 20% of the values being 0.

提交回复
热议问题