0

I want to create a 2d array with fixed number of True and False in each row. Here is the code to generate random array of True and False:

np.random.choice(a=[False, True], size=(N, N), p=[p, 1-p])

This code will give me an array of N*N with probability of p for False and 1-p for True. Now I want to set fixed number of False and True in each row, and also random. How can I do it in Python?

Here are some other related questions but are not the same as what I'm asking:

Example in C

Example in C#

Example but without specific number of True and False

Edit: I should add that also this link is not helpful for me as well. As it is seen in my question, I want to have a random boolean 2d array. So creating a 2d array and shuffling it won't be helpful ( shuffle is not shuffling the items independently, it can just move columns or rows), therefore it's not a random array. Please open my questions and let people answer it.

Paniz
  • 594
  • 6
  • 19

1 Answers1

0

If the wanted number of True (or False) values per row is one and only one :

# size of our array
M = 5 # rows
N = 3 # columns

# create an array full of "False"
foobar = np.full((M,N), False)

# create a list of randomly picked indices, one for each row
idx = np.random.randint(N, size=M)

# replace "False" by "True" at given indices
foobar[range(M), idx] = True

This approach won't work as is for multiple True values per row, though.

Skippy le Grand Gourou
  • 6,976
  • 4
  • 60
  • 76