Random Permutation
A random permutation rearranges the elements of an array in a random order. This is particularly useful in shuffling datasets, arranging seating orders, or creating randomized experiments.
Key Topics
Shuffling an Array
Use the shuffle()
method to modify an array by randomly shuffling its elements. This is done in place, meaning the original array is modified.
Example
# Shuffling an array
import numpy as np
students = np.array(["Arun", "Meera", "Karthik", "Nila", "Siva"])
np.random.shuffle(students)
print("Shuffled student list:", students)
Output
Shuffled student list: ['Meera' 'Siva' 'Arun' 'Nila' 'Karthik']
Explanation: The shuffle()
method randomizes the order of the array elements. Note that this operation modifies the original array.
Custom Permutations
Use the permutation()
method to generate a new array with randomized order while keeping the original array intact.
Example
# Generating a random permutation
numbers = np.array([1, 2, 3, 4, 5])
permuted_numbers = np.random.permutation(numbers)
print("Original array:", numbers)
print("Permuted array:", permuted_numbers)
Output
Original array: [1 2 3 4 5]
Permuted array: [4 1 5 3 2]
Permuted array: [4 1 5 3 2]
Explanation: The permutation()
method generates a new array with a random order, leaving the original array unchanged.
Key Takeaways
- Shuffling: Use
shuffle()
to randomize an array in place. - Permutation: Use
permutation()
to generate a new randomized array while keeping the original intact. - Applications: Shuffling datasets, creating random seating orders, or simulating experiments.