user10190803
user10190803

Reputation: 367

Selecting 3 random elements from an array in python

I am trying to select three random elements from within a array. I currently have implemented:

result= np.random.uniform(np.min(dataset[:,1]), np.max(dataset[:,1]), size=3

Which returns three random floats between the min and max range. I am struggling finding a way to select random elements within an array, instead of a random float which may not exist as an element inside the array.

I have also tried:

result = random.choice(dataset[:,0])

Which only returns a single element, is it possible to return 3 with this function

Upvotes: 1

Views: 4552

Answers (2)

Nicolaj Rasmussen
Nicolaj Rasmussen

Reputation: 169

You can use random.sample(), if you want to sample without replacement, ie. the same element can't be picked twice.

>>> import random
>>> l = [0.3, 0.2, 0.1, 0.4, 0.5, 0.6]
>>> random.sample(l, 3)
[0.3, 0.5, 0.1]

If you want to sample with replacement, you can random.choices()

>>> import random
>>> l = [0.3, 0.2, 0.1, 0.4, 0.5, 0.6]
>>> random.choices(l, k=3)
[0.3, 0.5, 0.3]

Upvotes: 8

blhsing
blhsing

Reputation: 106455

You can use random.choices instead:

result = random.choices(dataset[:,0], k=3)

Upvotes: 3

Related Questions