Python 以确定的数量1'随机初始化np数组;s和0';s
我想用一定数量的1和0随机初始化一个数组。下面的代码是我所有的。我只是设法用随机数1和0来初始化它,但我想这样做,例如(知道矩阵是10x10)用25个1和75个0Python 以确定的数量1'随机初始化np数组;s和0';s,python,arrays,numpy,random,Python,Arrays,Numpy,Random,我想用一定数量的1和0随机初始化一个数组。下面的代码是我所有的。我只是设法用随机数1和0来初始化它,但我想这样做,例如(知道矩阵是10x10)用25个1和75个0 matrix = np.random.randint(2, size=(10,10)) 简单:按顺序创建所需元素的数组,然后随机移动: # start with 100 zeroes arr = np.zeros((100,)) # change 25 of them to 1s arr[:25] = 1 # shuffle the
matrix = np.random.randint(2, size=(10,10))
简单:按顺序创建所需元素的数组,然后随机移动:
# start with 100 zeroes
arr = np.zeros((100,))
# change 25 of them to 1s
arr[:25] = 1
# shuffle the array to put all the elements in random positions
np.random.shuffle(arr)
# reshape to final desired shape
arr = arr.reshape((10,10))
简单:按顺序创建所需元素的数组,然后随机移动:
# start with 100 zeroes
arr = np.zeros((100,))
# change 25 of them to 1s
arr[:25] = 1
# shuffle the array to put all the elements in random positions
np.random.shuffle(arr)
# reshape to final desired shape
arr = arr.reshape((10,10))