Random Permutations

🔀 NumPy Random Permutations (Complete Guide)

Random permutation means randomly shuffling the elements of an array, either in-place or by creating a shuffled copy.
NumPy provides efficient methods for this.

All functions are in numpy.random.


✅ 1. shuffle() — Shuffle Array In-Place

Shuffles the elements without creating a new array.

import numpy as np
from numpy import random

arr = np.array([1, 2, 3, 4, 5])
random.shuffle(arr)
print(arr)

Output (example):

[3 5 1 4 2]

💡 Original array arr is modified.


✅ 2. permutation() — Return Shuffled Copy

Creates a new array and leaves the original unchanged.

arr = np.array([1, 2, 3, 4, 5])
perm = random.permutation(arr)
print("Original:", arr)
print("Shuffled:", perm)

Output (example):

Original: [1 2 3 4 5]
Shuffled: [4 1 5 3 2]

✅ 3. Permute 2D Arrays

  • shuffle() → shuffles rows only

  • permutation() → can shuffle rows or 1D flattened array

arr = np.array([[1,2],[3,4],[5,6]])

# Shuffle rows in-place
random.shuffle(arr)
print(arr)

# Shuffled copy
perm = random.permutation(arr)
print(perm)


✅ 4. Seed for Reproducibility

To get the same permutation every time:

random.seed(42)
arr = np.array([1, 2, 3, 4, 5])
print(random.permutation(arr))

✅ 5. Random Index Permutation

Sometimes you just need shuffled indices:

arr = np.array([10, 20, 30, 40, 50])
indices = random.permutation(len(arr))
shuffled_arr = arr[indices]
print(shuffled_arr)

🔄 Summary Table

Function Modifies Original? Returns New Array Notes
shuffle() ✅ Yes ❌ No In-place shuffling
permutation() ❌ No ✅ Yes Returns shuffled copy
random.permutation(n) ❌ No ✅ Yes Generates shuffled numbers from 0 to n-1

🎯 Practice Tasks

  1. Shuffle a 1D array of 20 elements.

  2. Shuffle rows of a 2D array 4×3.

  3. Use permutation() to randomly reorder [10, 20, 30, 40, 50] without changing original array.

  4. Generate a random index permutation and use it to shuffle an array.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *