Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling a numpy array with x random values

Tags:

python

numpy

I have a numpy array of size x, which I need to fill with 700 true.

For example:

a = np.zeros(5956)

If I want to fill this with 70 % True, I can write this:

msk = np.random.rand(len(a)) < 0.7
b = spam_df[msk]

But what if I need exactly 700 true, and the rest false?

like image 721
Oeyvind Avatar asked Sep 24 '26 13:09

Oeyvind


1 Answers

import numpy as np

x = 5956
a = np.zeros((x), dtype=bool)

random_places = np.random.choice(x, 700, replace=False)
a[random_places] = True
like image 187
Filip Młynarski Avatar answered Sep 26 '26 04:09

Filip Młynarski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!