NumPy Random Generator | permuted method
Start your free 7-days trial now!
NumPy Random's permuted(~)
method returns a new NumPy array with the values shuffled.
To shuffle values in-place, use shuffle(~)
.
Also, the difference between permutation(~)
and permuted(~)
is that the former shuffles rows or columns for two-dimensional arrays, but permuted(~)
shuffles values independent of the other rows or columns. Consult examples below for clarification.
Parameters
1. x
| NumPy array
or MutableSequence
The array to shuffle.
2. axis
link | int
| optional
The axis to shuffle. By default, axis=None
, which means that all the values in the array are shuffled.
3. out
| NumPy array
| optional
If given, then the result is stored in out
. By default, a new NumPy array is created and returned.
Return Value
A NumPy array.
Examples
Shuffling a one-dimensional array
To shuffle a one-dimensional array:
import numpy as nprng = np.random.default_rng(seed=42)rng.permuted([5,2,6,1])
array([1, 6, 2, 5])
Note that when shuffling one-dimensional arrays, the behaviour is exactly the same as permutation(~)
.
Shuffling two-dimensional array
Consider the following two-dimensional array:
Shuffling all values
By default, axis=None
, which means that all the values in the array are shuffled:
rng = np.random.default_rng(seed=42)rng.permuted(x) # axis=None
array([[ 0, 7, 6, 9], [11, 3, 5, 2], [ 4, 10, 1, 8]])
Shuffling values of each column
To shuffle the values in each column, set axis=0
:
rng = np.random.default_rng(seed=42)rng.permuted(x, axis=0)
array([[ 8, 1, 6, 11], [ 4, 9, 10, 3], [ 0, 5, 2, 7]])
Note that each row is shuffled independently on how the values in the other columns are sorted. This is the main difference between permuted(~)
and permutation(~)
.
Shuffling values of each row
To shuffle the values in each row, set axis=1
:
rng = np.random.default_rng(seed=42)rng.permuted(x, axis=1)
array([[ 3, 2, 1, 0], [ 7, 6, 4, 5], [ 8, 11, 10, 9]])