How to Randomly permute Numpy Array

In this post, we will learn how to permute or randomize a 1D array and 2D Numpy Array using Numpy. We will use Numpy’s Random Generator class to create generator object with default_rng() and use permutaion() function on the object to permute.

Let us get started by importing Numpy.

import numpy as np
# find Numpy version
np.__version__

1.24.0

The basic syntax of Numpy’s permutation function is

random.Generator.permutation(x, axis=0)

Here x can be an integer or array like object. A typical array like object is a Python list, 1D Numpy array, or a 2d Numpy array. When x is an integer, permutation() function uses the array from np.arange(x) as input. The second argument to permutation() function is axis and it is set to 0 by default. The axis argument is useful for permuting 2D arrays.

First, let us create a Random generator object using default_rng() function.

# Create a generator object
rng = np.random.default_rng()

Now we can use permutation function on the. integer to get randomly shuffled arrays containing integers 0 to 9.

# permute an array containing  0 to 9
rng.permutation(10)

array([5, 9, 4, 8, 1, 7, 2, 0, 6, 3])

As we mentioned above this is equivalent to providing np.arange(10) as input argument to permutation().

# Create a generator object
rng = np.random.default_rng()
rng.permutation(np.arange(10))

We can also permute elements in a Python list.

# permute a list of numbers
rng.permutation([1, 3, 5, 7, 9])

array([1, 3, 7, 9, 5])

Permute 2D Array with permutation() within columns

Let us first create a 2D array of dim 3×3 using Numpy’s arange() and reshape() functions.

arr = np.arange(9).reshape((3, 3))
arr

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

We can permute the matrix or 2D array using permutation() function. Note that the axis argument is 0 by default. Therefore the permutation() function will permute the 2D array by columns.

rng.permutation(arr)

array([[6, 7, 8],
       [0, 1, 2],
       [3, 4, 5]])

Here we explicitly specify the axis argument to 0 to permute by columns.

rng.permutation(arr, axis=0)

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

Permute 2D array by rows in Numpy

To permute the 2D matrix by rows we set the axis argument to 1. Now we can see that the 2D array is permuted within rows.

rng.permutation(arr, axis=1)

array([[2, 0, 1],
       [5, 3, 4],
       [8, 6, 7]])