Skip to main content

Introduction to Numpy Random Permutations

Numpy Random Permutations

n NumPy, you can generate random permutations of a sequence using the numpy.random.permutation() function. This function randomly shuffles the elements of the sequence and returns a new shuffled sequence.

As an example:

import numpy as np

# Create an array of numbers
arr = np.array([1, 2, 3, 4, 5])

# Generate a random permutation of the array
permuted_arr = np.random.permutation(arr)
print(permuted_arr) # Output: [2 4 1 5 3]

In this example:

  • We have an array arr containing the numbers [1, 2, 3, 4, 5].
  • The np.random.permutation(arr) function is used to generate a random permutation of the array.
  • The resulting permuted_arr contains the shuffled elements of the original array.

You can also apply the np.random.permutation() function to other sequences such as lists or strings.

Here's an example with a list:

import numpy as np

# Create a list of names
names = ['Alice', 'Bob', 'Charlie', 'David']

# Generate a random permutation of the list
permuted_names = np.random.permutation(names)
print(permuted_names) # Output: ['Bob' 'Alice' 'David' 'Charlie']

In this example:

  • The np.random.permutation(names) function shuffles the elements of the names list to produce a random permutation.
tip

The np.random.permutation() function does not modify the original sequence. It returns a new shuffled sequence. If you want to modify the original sequence in-place, you can use the np.random.shuffle() function instead

Shuffling Arrays

Shuffle the elements of an array in-place using the numpy.random.shuffle() function. This function randomly reorders the elements of the array.

As an example:

import numpy as np

# Create an array of numbers
arr = np.array([1, 2, 3, 4, 5])

# Shuffle the array in-place
np.random.shuffle(arr)
print(arr) # Output: [4 2 1 5 3]

In this example:

  • We have an array arr containing the numbers [1, 2, 3, 4, 5].
  • The np.random.shuffle(arr) function shuffles the elements of the array, modifying it in-place.
  • The resulting array arr contains the shuffled elements.

Shuffle multi-dimensional

You can also apply the np.random.shuffle() function to multi-dimensional arrays. It shuffles the elements along the first axis (rows) of the array.

As an example:

import numpy as np

# Create a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Shuffle the rows of the array in-place
np.random.shuffle(arr)
print(arr)

Output:

[[7 8 9]
[4 5 6]
[1 2 3]]

In this example:

  • The np.random.shuffle(arr) function shuffles the rows of the 2D array, modifying it in-place.
info

Note that np.random.shuffle() shuffles the array along the first axis. If you have a 1D array, it will shuffle the elements. If you have a 2D array, it will shuffle the rows.