NumPy Random Generator | permutation method
Start your free 7-days trial now!
NumPy Random Generator's permutation(~) method return a new 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 | int or array-like
- If - xis an- int, then a- np.arange(x)is randomly shuffled and returned.
- If - xis- array-like, then a new array with randomly shuffled values is returned.
2. axis | int | optional
The axis by which to perform the shuffling. By default, axis=0.
Return Value
A NumPy array.
Examples
Passing an integer
To get a shuffled array of [0,1,2,3,4]:
        
        
            
                
                
                    import numpy as nprng = np.random.default_rng(seed=42)rng.permutation(5)
                
            
            array([4, 2, 3, 1, 0])
        
    Note that this is equivalent to rng.permutation(np.arange(5)).
Passing in an array
To randomly shuffle an array of numbers:
        
        
            
                
                
                    rng = np.random.default_rng(seed=42)rng.permutation([5,2,6,1])
                
            
            array([1, 6, 2, 5])
        
    Note that when shuffling one-dimensional arrays, the behaviour is exactly the same as permuted(~).
Setting axis
Consider the following two-dimensional array:
        
        
    Shuffling the rows
By default, axis=0, which means that the rows are randomly shuffled (in a two-dimensional array):
        
        
            
                
                
                    rng = np.random.default_rng(seed=42)rng.permutation(x)   # axis=0
                
            
            array([[ 8,  9, 10, 11],       [ 4,  5,  6,  7],       [ 0,  1,  2,  3]])
        
    Shuffling the columns
To randomly shuffle the columns of a two-dimensional array:
        
        
            
                
                
                    rng = np.random.default_rng(seed=42)rng.permutation(x, axis=1)
                
            
            array([[ 3,  2,  1,  0],       [ 7,  6,  5,  4],       [11, 10,  9,  8]])
        
    