0

I have a numpy array populated with zeros and ones and after the array is created I need to replace some of the zeros with ones. Here is my code for the array:

grid = np.random.randint(0, 2, size=(4,4)) 
np.random.shuffle(grid)

I tried:

grid[grid == 0] = np.random.binomial(1, 0.9, size = None)

and:

grid[grid == 0] = np.random.randint(0, 2)

But then all the zeros are replaced with 1 or not replaced at all. Is there a way to replace only some of the zeros?

1
  • Yes, you need a way to identify just the elements/items that you want to replace - grid == 0 specifies all zeroes. There are a few ways that you can index an ndarray. - docs.scipy.org/doc/numpy/user/basics.indexing.html Commented Nov 30, 2017 at 16:37

3 Answers 3

1

How about this:

grid += np.random.binomial(1, 0.9, size=grid.shape) * (grid == 0)
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of a single draw, draw multiple times

grid = np.random.randint(0, 2, size=(4,4))
np.random.shuffle(grid)

grid[grid==0] = np.random.binomial(1, 0.5, size = grid[grid==0].shape[0])

Comments

0

You better try again.

for me the shuffle method works.

np.random.shuffle(grid)

although seems to work only after applying it twice....

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.