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?
Asked
Active
Viewed 208 times
4

Dom White
- 43
- 3
-
"I'd also rather not iteratively append new rows to a matrix" this includes list comprehension? – Hemerson Tacon Oct 16 '18 at 13:46
2 Answers
1
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

piripiri
- 1,925
- 2
- 18
- 35
0
You could use list comprehension:
data = np.array([np.random.choice([1,2,3], 3, replace=False) for _ in range(3)])

Hemerson Tacon
- 2,419
- 1
- 16
- 28