Random Permutations of Elements in NumPy
A permutation refers to a rearrangement of elements in an array. For example, [3, 2, 1] is a permutation of [1, 2, 3].
In Python, the NumPy Random module provides two useful methods for working with permutations:
shuffle()
permutation()
Shuffling Arrays with shuffle()
The shuffle() method randomly rearranges the elements of an array in-place. This means the original array itself gets modified.
Program:
from numpy import random
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
random.shuffle(arr)
print(arr)
Output:
[2 4 3 5 1]
In this example, the order of elements in arr will be randomly changed.
Note: Since it works in-place, the original array is altered.
Generating Random Permutations with permutation()
If you want to generate a random permutation without modifying the original array, use permutation(). It returns a new array with shuffled elements, keeping the original array unchanged.
Program:
from numpy import random
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(random.permutation(arr))
Output:
[2 3 4 5 1]