VansFannel
VansFannel

Reputation: 45991

Create a numpy array with zeros and ones at random positions

I'm using Python 3.7.7.

I want to create a Numpy array with random values between 1 and 0. I have found that I can create an array with all of its elements equal to zero:

zeros = np.zeros((960, 200, 200, 1))

Or equal to one:

ones = np.ones((960, 200, 200, 1))

Those functions return an array with all of its elements equals.

I want to create an array with its elements are zero or one at random positions.

How can I do it?

Upvotes: 0

Views: 3585

Answers (2)

efont
efont

Reputation: 246

This can be achieved in many ways using numpy, the most straightforward being:

size = (960, 200, 200, 1)
np.random.randint(0, 2, size=size)

If you don't want uniform distribution of zeros and ones, this can be controlled directly using numpy.random.choice:

size = (960, 200, 200, 1)
proba_0 = 0.8                 # resulting array will have 80% of zeros
np.random.choice([0, 1], size=size, p=[proba_0, 1-proba_0])

Upvotes: 5

warped
warped

Reputation: 9491

you can draw numbers from [0,1] and ask if they are larger than a threhold value:

threshold = 0.5
a = 1*(np.random.rand(960, 200, 200, 1)> threshold)

Upvotes: 1

Related Questions