2

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.

5
  • 1
    Shuffle a 1D array and reshape it to the 2D shape you want. Commented Feb 26, 2019 at 0:52
  • 1
    @user2357112 I want to have have the same number of True and False in each row. It's not working Commented Feb 26, 2019 at 0:57
  • "I want to have have the same number of True and False in each row" - that wasn't in your question. Commented Feb 26, 2019 at 0:59
  • @user2357112 Ok. Edited. Commented Feb 26, 2019 at 14:45
  • @user2357112 Can I remove it and post it as a new question? Commented Feb 26, 2019 at 18:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Does it work if we just want one item per row to be False?
@Paniz Sure, just switch the two occurrences of True and False. Actually it would work with any couple of values, they don't have to be boolean.
I need to have specific number of True and False in each row. It just works when we have one True ( the rest False) or one False ( the rest True) in each row.
@Paniz Indeed, and this point was highlighted in the first sentence of my answer. ;)
True. Thanks a lot
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.