![]() |
VOOZH | about |
Randomly selecting elements from an array means choosing random elements from the array. NumPy offers several efficient methods to pick elements either with or without repetition. For example, if you have an array [1, 2, 3, 4, 5] and want to randomly select 3 unique elements, the output might look like [1 5 2]. Let’s explore different methods to do this efficiently.
This method randomly selects elements from an array without repetition. It’s useful when you need unique random samples of a given size.
[2 5 4]
Explanation: np.random.choice(a, size=3, replace=False)selects 3 unique random elements from the array a, where size=3 means 3 values are chosen, and replace=Falseensures no repetition.
This shuffles the array in-place, meaning the original array is modified. It's very fast and memory-efficient; just take the first n values after shuffle.
[1 4 2]
Explanation: np.random.shuffle(a) randomly shuffles the elements of array a in-place, changing the original order. res = a[:3] then selects the first 3 elements from the shuffled array.
This method returns a new shuffled copy of the original array. The original array remains unchanged, making it safer for reuse.
[1 2 5]
Explanation: np.random.permutation(a) returns a shuffled copy of array a without modifying the original. res = b[:3] selects the first 3 elements from this shuffled copy.
This allows sampling with repetition, so the same value can appear multiple times. It’s useful when you need more samples than unique elements.
[5 2 1]
Explanation: np.random.choice(a, size=3, replace=True) randomly selects 3 elements from array a, allowing repetition. This means the same element can appear multiple times in the result.