2

Suppose I have a binary matrix. I would like to cast that matrix into another matrix where each row has single one and the index of that one would be random for each row.

For instance if one of the row is [0,1,0,1,0,0,1] and I cast it to [0,0,0,1,0,0,0] where we select the 1's index randomly.

How could I do it in numpy?

Presently I find the max (since max function returns one index) of each row and set it to zero. It works if all rows have at most 2 ones but if more than 2 then it fails.

1
  • 1
    Why the "Matlab" label? do you also want answers in Matlab? Commented Feb 19, 2014 at 16:06

2 Answers 2

3

Extending @zhangxaochen's answer, given a random binary array

x = np.random.random_integers(0, 1, (8, 8))

you can populate another array with a randomly drawn 1 from x:

y = np.zeros_like(x)
ind = [np.random.choice(np.where(row)[0]) for row in x]
y[range(x.shape[0]), ind] = 1
Sign up to request clarification or add additional context in comments.

Comments

2

I'd like to use np.argsort to get the indices of the non-zero elements:

In [351]: a=np.array([0,1,0,1,0,0,1])

In [352]: from random import choice
     ...: idx=choice(np.where(a)[0]) #or np.nonzero instead of np.where

In [353]: b=np.zeros_like(a)
     ...: b[idx]=1
     ...: b
Out[353]: array([0, 1, 0, 0, 0, 0, 0])

1 Comment

You can replace a.argsort()[-np.count_nonzero(a):] with np.where(a)[0].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.