Permutation and Shuffling

January 22, 2018

Permutation and Shuffling

In addition to providing functions for random number generation and sampling from distributions, NumPy’s random module also allows us to perform permutation and shuffling on existing lists.


Import Libraries

import numpy as np


If you have a list that you do not wish to change the ordering (or unable to as the data is immutable, such as a DataFrame’s index), but would want to generate a randomised version of it, you can utilise the permutation function.

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
print(np.random.permutation(numbers))
[3 1 4 7 8 5 2 6]


The shuffle function has the same functionality as permutation, except that it will be performed inplace.

print('The original list: ' + str(numbers))
np.random.shuffle(numbers)
print('The shuffled list: ' + str(numbers))
The original list: [1, 2, 3, 4, 5, 6, 7, 8]
The shuffled list: [4, 3, 2, 8, 7, 1, 6, 5]
comments powered by Disqus