
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Permutations and Shuffling
What are Permutations and Shuffling?
Permutations and shuffling are techniques used to rearrange the elements of an array in a random order. While shuffling modifies the array in place, permutations create a new array with the elements rearranged.
These operations are useful for tasks such as data augmentation, bootstrapping, and testing the robustness of algorithms.
Shuffling Arrays with NumPy
NumPy provides the numpy.random.shuffle() function to shuffle the elements of an array in place. This means that the original array is modified, and the elements are rearranged randomly.
Example
As shown in the example below, the elements of the array are shuffled in place, meaning the original array is modified, and the elements are rearranged randomly −
import numpy as np # Define an array array = np.array([1, 2, 3, 4, 5]) # Shuffle the array in place np.random.shuffle(array) print("Shuffled array:", array)
Following is the output obtained −
Shuffled array: [1 2 5 4 3]
Generating Permutations with NumPy
Unlike shuffling, permutations create a new array with the elements rearranged randomly without modifying the original array. NumPy provides the numpy.random.permutation() function to generate permutations.
Example
In the following example, the original array remains unchanged, and a new array with the elements rearranged randomly is generated −
import numpy as np # Define an array array = np.array([1, 2, 3, 4, 5]) # Generate a permutation of the array permuted_array = np.random.permutation(array) print("Original array:", array) print("Permuted array:", permuted_array)
This will produce the following result −
Original array: [1 2 3 4 5] Permuted array: [4 2 5 1 3]
Shuffling Multidimensional Arrays
NumPy also supports shuffling multidimensional arrays. When you shuffle a multidimensional array, only the first axis is shuffled.
Example
In this example, only the rows of the 2D array are shuffled, while the elements within each row remain in their original order −
import numpy as np # Define a 2D array array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Shuffle the array in place np.random.shuffle(array_2d) print("Shuffled 2D array:", array_2d)
Following is the output of the above code −
Shuffled 2D array: [[4 5 6] [1 2 3] [7 8 9]]
Permuting Multidimensional Arrays
Similar to shuffling, you can generate permutations of multidimensional arrays. When using the numpy.random.permutation() function, the array is flattened, permuted, and then reshaped to its original dimensions.
Example
In this example, the rows of the 2D array are permuted, creating a new array with the rows rearranged in a different order −
import numpy as np # Define a 2D array array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Generate a permutation of the 2D array permuted_array_2d = np.random.permutation(array_2d) print("Original 2D array:", array_2d) print("Permuted 2D array:", permuted_array_2d)
The output obtained is as shown below −
Original 2D array: [[1 2 3] [4 5 6] [7 8 9]] Permuted 2D array: [[1 2 3] [4 5 6] [7 8 9]]
Random Permutations of Integers
NumPy can also generate random permutations of a range of integers using the numpy.random.permutation() function. This is useful for creating random sequences of integers.
Example
Following is an example to generate a random permutation of integers from 0 to 9 using the numpy.random.permutation() function −
import numpy as np # Generate a random permutation of integers from 0 to 9 random_permutation = np.random.permutation(10) print("Random permutation of integers from 0 to 9:", random_permutation)
Following is the output obtained −
Random permutation of integers from 0 to 9: [2 8 1 3 4 0 6 7 5 9]
Shuffling with a Specific Seed
To ensure reproducibility, you can set a specific seed before shuffling or generating permutations. This ensures that the same sequence of random numbers is generated each time you run the code.
Example
By setting the seed, you ensure that the random shuffling produces the same result every time the code is executed as shown in the example below −
import numpy as np # Set the seed for reproducibility np.random.seed(42) # Define an array array = np.array([1, 2, 3, 4, 5]) # Shuffle the array in place np.random.shuffle(array) print("Shuffled array with seed 42:", array) # Reset the seed and shuffle again to get the same result np.random.seed(42) np.random.shuffle(array) print("Shuffled array with seed 42 (again):", array)
The output obtained is as shown below −
Shuffled array with seed 42: [2 5 3 1 4] Shuffled array with seed 42 (again): [5 4 3 2 1]
Shuffling and Permutations for Data Splitting
Shuffling and permutations are commonly used in machine learning for splitting datasets into training and testing sets. By randomly shuffling the data, you ensure that the training and testing sets are representative of the overall dataset.
Example
In this example, the dataset is shuffled, and then split into training and testing sets. This helps in ensuring that the training and testing sets are randomly distributed and representative of the overall dataset −
import numpy as np # Define a dataset dataset = np.array([[1, 'A'], [2, 'B'], [3, 'C'], [4, 'D'], [5, 'E']]) # Shuffle the dataset in place np.random.shuffle(dataset) print("Shuffled dataset:", dataset) # Split the dataset into training and testing sets train_set = dataset[:3] test_set = dataset[3:] print("Training set:", train_set) print("Testing set:", test_set)
Following is the output obtained −
Shuffled dataset: [['5' 'E'] ['4' 'D'] ['2' 'B'] ['1' 'A'] ['3' 'C']] Training set: [['5' 'E'] ['4' 'D'] ['2' 'B']] Testing set: [['1' 'A'] ['3' 'C']]