What is random permutation of an array from NumPy in Python?

Overview

The Random module in NumPy helps make permutations of elements of an array.

Permutation refers to the arrangement of elements in an array. For example, [3, 1, 2] and [1, 3, 2] are permutations of the array elements in [1, 2, 3] and vice versa.

Methods of random permutation of elements

To make a permutation of elements in an array, we need to choose either of these two methods:

  1. Shuffle() method
  2. Permutation() method

The shuffle() method

The shuffle() method changes or “shuffles” the arrangements of elements in an array randomly. This method modifies the original array.

Syntax

random.shuffle(array)

Parameter value

The shuffle() method takes a single parameter value: an array object.

Code example

from numpy import random, array
from random import shuffle
# creating an array
my_array = array([1, 2, 3, 4, 5])
# calling the shuffle() method
shuffle(my_array)
print(my_array)

Code explanation

  • Line 1: We import the random and array modules from numpy.
  • Line 2: We import the shuffle method from random module.
  • Line 5: We create an array my_array using the array() function.
  • Line 8: We call the shuffle() method on the array my_array.
  • Line 10: We print the modified array my_array.

The permutation() method

The permutation() method is the same as the shuffle() method, but it returns a re-arranged array and does not modify the original array.

Syntax

random.permutation(array)

Parameter value

The permutation() method takes a single parameter value: an array object.

Code example

from numpy import random, array
from random import permutation
# creating an array
my_array = array([1, 2, 3, 4, 5])
# calling the permutation() method
print(permutation(my_array))
print(my_array)

Code explanation

  • Line 1: We import the random and array modules from numpy.
  • Line 4: We create an array my_array using the array() function.
  • Line 7: We call the permutation() method on the array my_array and print the re-arranged array.
  • Line 9: To show that the permutation() function does not modify the original array, we print the array my_array.

Free Resources