I can easily use np.random.choice with replace=False to generate a 1D array without replacement. However, I need to generate a matrix such that each row is without replacement, i.e.[[1, 2, 3], [2, 3, 1], [3, 1, 2]]. np.random.randint is the obvious choice, but there's no provision for non-repetition in this function. I'd also rather not iteratively append new rows to a matrix, as I imagine this is rather inefficient. So, what is the most efficient way to generate my matrix?
You can first create your whole array and then use np.random.shuffle for shuffling your rows.
n = 3
data = np.arange(n*n).reshape(n, n) % n + 1
for row in data:
np.random.shuffle(row)
Here, the modulo operator is used for producing numbers from 0 to (n-1) in each row.
As an alternative,
data = np.empty(shape=(3, 3))
reserves the memory for an empty array that can afterwards be filled more efficiently:
for i in range(len(data)):
data[i,:] = np.random.choice(3, 3, replace=False) + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With