简体   繁体   中英

How to set the sum of each row in an array equal to 1?

I'm not sure if I need a for loop in order to set each row equal to 1? I'm trying to make a two dimensional array with random integers where the sum of each row is 1.

import numpy as np

a = np.random.randint(1,2, size = (13,17))

The only way you will get a 2D array of positive integers with rows that sum to 1 is if each row contains all zeros and a single one. This could be done using something like this

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]])

"Create a two-dimensional, 13 by 17 array of random, positive entries such that the sum of each row is 1."

If the entries should be integers as you write in your question, then

a = np.zeros((13,17), dtype=np.uint8)
a[np.arange(13), np.random.randint(0,13, size=13)] = 1

Otherwise:

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.])

If you want positive numbers (not integers), then create your matrix as random numbers between 0 and 1 and normalise each row:

a = np.random.rand(17,12)
a = a/np.linalg.norm(a, ord=2, axis=1, keepdims=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM