numpy 如何在python中生成一个随机的0和1的矩阵,其中每行的和等于10

nbewdwxp  于 2022-11-24  发布在  Python
关注(0)|答案(4)|浏览(261)

我如何生成一个随机(N*M)0和1的矩阵,其中每行的和等于10?(在python中使用numpy)
例如,对于10*10(N*M)矩阵,我们可以用途:

import numpy as np
np.random.randint(2, size=(10, 10))

但我希望每行的和等于10

evrscar2

evrscar21#

这不一定是最有效的方法,但它很简洁:

In [29]: rng = np.random.default_rng(121263137472525314065)

In [30]: n_rows = 5

In [31]: n_cols = 20

In [32]: n_ones = 10

In [33]: rng.multivariate_hypergeometric([1]*n_cols, n_ones, size=n_rows)
Out[33]: 
array([[0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1],
       [1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0],
       [0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1],
       [0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1],
       [1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0]])
7dl7o3gd

7dl7o3gd2#

或者,分配0和1的数组,并对每行进行混洗:

import numpy as np

n_rows = 5
n_cols = 20
n_ones = 10

arr = np.tile(np.repeat([0, 1], [n_ones, n_cols-n_ones]), (n_rows,1))
# [[0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]
#  [0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]
#  [0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]
#  [0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]
#  [0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]]
np.apply_along_axis(np.random.shuffle, 1, arr) # operates on arr inplace
# [[1 1 0 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 1 1]
#  [1 0 1 1 0 1 1 0 0 0 1 0 1 0 1 1 0 0 1 0]
#  [1 1 0 1 0 0 0 1 0 0 1 1 0 0 1 0 1 1 1 0]
#  [1 0 0 1 0 0 0 1 0 0 1 1 0 1 1 0 1 0 1 1]
#  [1 1 1 0 1 0 1 0 1 0 1 0 1 0 0 1 1 0 0 0]]
zwghvu4y

zwghvu4y3#

您可以为每行随机抽取10个索引

def make_thing(n):
    if n <= 10:
       return np.ones((10,10))
    
    matrix = np.zeros((n, n))
    for row in range(n):
        ten_random_index = random.sample(range(n),10)
        matrix[row][ten_random_index] = 1
    return matrix

也可以预定义一行

row = [1]*10 + [0]*(n-10)
matrix = numpy.array([random.sample(row,n) for _ in range(n)])
k5hmc34c

k5hmc34c4#

您可以使用下面的函数来获得一个随机矩阵,其中包含1和0,并且行和等于10:

def matrix_generator(n_rows, n_columns):
    if n_columns < 10:
        print('Number of rows need to be greater than or equal to 10.')
        return 0
    
    row_list = [1,1,1,1,1,1,1,1,1,1]
    add_columns = n_columns-10

    for i in range(add_columns):
        row_list.append(0)
    
    matrix = [[]]*n_rows
    
    for i in range(n_rows):
        random.shuffle(row_list)
        matrix[i] = row_list[:]
    
    random.shuffle(matrix)
    
    return matrix

相关问题