Search code examples
pythonnumpyvector

How can I create a numpy vector of size n containing 0 or 1 randomly?


I know that np.zeros(n) creates an n-dimensional vector containing only zeros in python.

Is there an easy way to get an n-dimensional vector containing randomly zeros or ones as integer values?

I tried to find an answer here but I didn't succeed.


Solution

  • There are many options. Here are two possible ways using NumPy:

    import numpy as np
    n = 10
    
    np.random.randint(0, 2, size=n)
    
    np.random.choice([0,1], size=n)
    

    Both will output something like this:

    array([0, 0, 1, 0, 1, 0, 0, 0, 1, 0])
    

    Here is the relevant documentation:

    https://numpy.org/doc/stable/reference/random/generated/numpy.random.randint.html

    https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html