Gaslight Deceive Subvert
Gaslight Deceive Subvert

Reputation: 20354

How do I set random elements in a 2d numpy array without looping?

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?

Upvotes: 1

Views: 211

Answers (1)

Fruity Medley
Fruity Medley

Reputation: 564

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

Upvotes: 1

Related Questions