Home »
Python »
Python Programs
shuffle vs permute numpy
Learn about the difference between NumPy's shuffle method and permute method.
By Pranit Sharma Last updated : October 09, 2023
NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.
NumPy - shuffle vs permute Methods
Numpy's random.shuffle() method modifies a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remain the same.
Numpy's random.permute() randomly permute a sequence, or return a permuted range. If x is a multi-dimensional array, it is only shuffled along its first index.
Basically, np.random.permutation() has two differences from np.random.shuffle():
- If passed an array, it will return a shuffled copy of the array;
np.random.shuffle() shuffles the array in place
- if passed an integer, it will return a shuffled range i.e. np.random.shuffle(np.arange(n))
Let us understand with the help of an example,
Python program to demonstrate the example of NumPy's shuffle vs permute methods
# Import numpy
import numpy as np
# Creating an array
arr = np.arange(10)
# Display original array
print("Original Array:\n",arr,"\n")
# Shuffling array
np.random.shuffle(arr)
# Display result
print("Shuffled array:\n",arr,"\n")
# using permutation method
res = np.random.permutation(arr)
# Display result
print("Permuted array:\n",res)
Output
The output of the above program is:
Python NumPy Programs »