'How do you make a pandas dataframe be filled randomly with 1s and 0s?

I have a pandas dataframe in python that I would like to fill with 1s and 0s based on random choices. If possible, I'd like it to be done with numpy. I've tried

tw['tw'] = np.random.choice([0, 1])

but this ends up just giving me a dataframe filled with either a 1 or a 0. I know that this is possible using a for loop:

for i in range(len(tw)):
    tw['tw'][i] = np.random.choice([0, 1])

But this feels inefficient. How might I go about doing this?



Solution 1:[1]

If you assign a scalar, the value will be broadcasted to all indices.

You need to assign an array of the size of the Series.

Use the size parameter of numpy.random.choice:

tw['tw'] = np.random.choice([0, 1], size=len(tw))

Solution 2:[2]

You can use numpy's random integer generator

tw['tw'] = np.random.randint(low = 0,high = 2,size = len(tw))

Note that the "high" number is non-inclusive, so you'd have to give 2.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sunderam Dubey
Solution 2 Sunderam Dubey