NumPy - random.permutation() function

The NumPy random.permutation() function randomly permutes a sequence or an array, and returns it. If x is a multi-dimensional array, it is only shuffled along its first axis.

Syntax

numpy.random.permutation(x)

Parameters

 x Required. Specify the array or list to be permuted. If x is an integer, randomly permute np.arange(x).

Return Value

Returns permuted sequence or array range.

Example:

In the example below, random.permutation() function is used to permute the content of a given list.

import numpy as np

x = np.arange(0, 10)
y = np.random.permutation(x)

#displaying the content of x and y
print("x contains:", x)
print("y contains:", y)

The output of the above code will be:

x contains: [0 1 2 3 4 5 6 7 8 9]
y contains: [8 5 0 1 4 6 2 9 7 3]

Example:

When the function is used with a multi-dimensional array, it permutes the content only along first axis.

import numpy as np

x = np.arange(1, 10).reshape(3,3)
y = np.random.permutation(x)

#displaying the content of x
print("x contains:")
print(x)

#displaying the content of y
print("\ny contains:")
print(y)

The output of the above code will be:

x contains:
[[1 2 3]
[4 5 6]
[7 8 9]]

y contains:
[[4 5 6]
[7 8 9]
[1 2 3]]

Example:

When the function is used integer, it randomly permute np.arange(x) as shown in the example below.

import numpy as np

x = np.random.permutation(7)

#displaying the content of x
print("x contains:", x)

The output of the above code will be:

x contains: [2 6 5 3 1 4 0]

❮ NumPy - Random

5