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.
Output (example):
💡 Original array arr is modified.
✅ 2. permutation() — Return Shuffled Copy
Creates a new array and leaves the original unchanged.
Output (example):
✅ 3. Permute 2D Arrays
-
shuffle()→ shuffles rows only -
permutation()→ can shuffle rows or 1D flattened array
✅ 4. Seed for Reproducibility
To get the same permutation every time:
✅ 5. Random Index Permutation
Sometimes you just need shuffled indices:
🔄 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
-
Shuffle a 1D array of 20 elements.
-
Shuffle rows of a 2D array 4×3.
-
Use
permutation()to randomly reorder[10, 20, 30, 40, 50]without changing original array. -
Generate a random index permutation and use it to shuffle an array.
