user5368737
user5368737

Reputation: 803

Using np.random.randint as fill_value

I want to create a numpy array, where each element is the amount of 1s in another numpy array of size x created with np.random.randint.

>>> x = 10
>>> np.random.randint(2, size=x)
array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])
>>> sum(array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1]))
5

and using it like this results in the same array being used, instead of generating a new random one each time

>>> np.full((5,), sum(np.random.randint(2, size=10)), dtype="int")
array([5, 5, 5, 5, 5])

How can I do this, or is there a better way to do this? I also tried the following

>>> a = np.random.rand(10)
>>> len(a[a < 0.5])
7
>>> np.full((5,), len(np.random.rand(10)[np.random.rand(10) < 0.5]), dtype="int")
array([7, 7, 7, 7, 7])

but as you can see that also resulted in the same numbers. The problem is that I don't want to use for loops, and instead find a way to do it quickly using numpy.

Upvotes: 0

Views: 421

Answers (2)

languitar
languitar

Reputation: 6784

Using the binomial distribution as discussed above:

In [13]: np.random.binomial(10, 0.5, 5)
Out[13]: array([7, 4, 6, 7, 4])

This assumes that there are 10 distinct left/right decisions, each having 0.5 probability.

Upvotes: 0

Ed Smith
Ed Smith

Reputation: 13196

You could just generate a matrix which is N arrays each of size x made of random ints. Then sum over each array,

import numpy as np
x = 10
N = 5
a = np.sum(np.random.randint(2, size=[N,x]),0)

I'm fairly sure np.full is not what you want here as this is for array initialisation to a single value.

Upvotes: 1

Related Questions