1

I have a 2d array of zeros onto which I want to set some random elements to ones. First the rows are selected and then the columns, like this:

>>> A = np.zeros((100, 50))
>>> rows = np.random.choice(100, size = 10, replace = False)
>>> cols = np.random.randint(50, size = 10)
>>> A[rows][cols] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 24 is out of bounds for axis 0 with size 10

Of course I can solve the problem with an explicit loop:

>>> for row in rows: A[row][np.random.randint(50)] = 1

But I don't want to. Can what I want to do be accomplished using numpy without explicit looping?

8
  • 4
    A[rows,cols] = 1 Commented Oct 30, 2019 at 13:45
  • You use the same axis twice. A[rows] returns set of row, so its shape is 10,50. Then you try again to get rows of that slice. Commented Oct 30, 2019 at 13:48
  • I don't see the difference to just initiating an array with 0's and 1's. Wouldn't np.random.randint(0, 2, (100, 50)) also solve your problem? Commented Oct 30, 2019 at 13:50
  • @user8408080 OP wants only 10 ones Commented Oct 30, 2019 at 13:54
  • But then randint won't help either, because it could potentially yield the same pair of numbers twice Commented Oct 30, 2019 at 13:56

1 Answer 1

1

Provide all indexes in one set of brackets, like so
A[rows,cols] = 1

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

Comments

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.