Home » 
        Python » 
        Python Programs
    
        
    Python - numpy.random.permutation() Method (With Examples)
    
    
    
    
        
            By IncludeHelp Last updated : September 14, 2024
        
    
    Description and Usage
Python's numpy.random.permutation() method returns a random permutation of a sequence (usually a numpy array) where permutation refers to as the total possible rearrangements for a given sequence.
Syntax
Below is the syntax of the method:
numpy.random.permutation(x)
Parameter
x: It can be an integer or an array-like object (e.g., a list or numpy array)
Return Values
It returns a permuted sequence or array.
Detailed Explanation
For example, the total possible permutations for sequence [1,2,3] are: [1,2,3], [1,3,2], [2,1,3 ], [2,3,1], [3,1,2], [3,2,1].
Now, with the help of numpy.random.permutation(), we can randomly select any of the permutations of the above sequence.
This function takes an input array or an int value. If an array is 2-dimensional, it shuffles the values along its rows.
If an int value is passed (say n), it creates a sequence from 0 to n and returns a random permutation of the created sequence.
Example 1: Giving a sequence as input
# Import numpy
import numpy as np
# Creating a numpy array
arr = np.array([32, 524, 4, 2, 22, 4, 54, 3445, 564, 46, 33, 3, 3, 73, 26])
# Display Original array
print("Original array:\n", arr, "\n")
# Selecting a random permutation of the array
res = np.random.permutation(arr)
# Display randomly selected permutation
print("Randomly selected permutation:\n", res)
Output
Original array:
 [  32  524    4    2   22    4   54 3445  564   46   33    3    3   73
   26] 
Randomly selected permutation:
 [  32   73  564   22   33  524   54   26   46    3 3445    2    3    4
    4]
Example 2: Giving an int value as input
# Import numpy
import numpy as np
# Selecting a random permutation
res = np.random.permutation(10)
# Display randomly selected permutation
print("Randomly selected permutation:\n", res)
Output
Randomly selected permutation:
 [1 0 5 6 9 7 3 2 4 8]
    Python NumPy Programs »
	
    
    
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement