Python 如何将数组中每行的总和设置为1?
我不确定是否需要for循环才能将每一行设置为1?我想用随机整数做一个二维数组,其中每行的和是1Python 如何将数组中每行的总和设置为1?,python,python-3.x,numpy,Python,Python 3.x,Numpy,我不确定是否需要for循环才能将每一行设置为1?我想用随机整数做一个二维数组,其中每行的和是1 将numpy导入为np a=np.random.randint(1,2,size=(13,17)) 如果需要正数(而不是整数),则将矩阵创建为0到1之间的随机数,并对每行进行归一化处理: a = np.random.rand(17,12) a = a/np.linalg.norm(a, ord=2, axis=1, keepdims=True) 获得行和为1的二维正整数数组的唯一方法是,每行包含所有
将numpy导入为np
a=np.random.randint(1,2,size=(13,17))
如果需要正数(而不是整数),则将矩阵创建为0到1之间的随机数,并对每行进行归一化处理:
a = np.random.rand(17,12)
a = a/np.linalg.norm(a, ord=2, axis=1, keepdims=True)
获得行和为1的二维正整数数组的唯一方法是,每行包含所有零和一个一。这可以用这样的方法来实现
import numpy as np
# get 2D array of zeros
a = np.zeros((13, 17)).astype(int)
# loop over each row
for row in range(len(a)):
# place a one at a random index in each row
idx = np.random.choice(len(a[0]))
a[row, idx] = 1
print(a)
Out[48]:
array([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
创建一个由13×17个随机正数项组成的二维数组,使每行的总和为1
如果你在问题中写的条目应该是整数,那么
a = np.zeros((13,17), dtype=np.uint8)
a[np.arange(13), np.random.randint(0,13, size=13)] = 1
否则:
a = np.random.randint(0, 10, size = (13,17)) # instead of 10 you can use any value >= 2
a = a / a.sum(1, keepdims=True)
# Check
a.sum(1)
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
它们可以是负数吗?预期的界限是什么?你的问题中的区间
[1,2)
只包含1
。将每列除以范数1如果整数为正,则每行将包含12个零和1个。将每行除以其总和。在完整的问题中,它表示“随机、正条目”,不是你写的必要整数?这不是一个需要解释的答案