Skip to main content
Documents
basicsArray CreationArray OperationsArray Computation & AnalysisLinear AlgebraRandom ProbabilityData Input/Output & Conversion

NumPy random.shuffle()

NumPy's Random & Probability module provides functions to generate and manipulate random numbers, essential for simulations and randomized operations. The `numpy.random.shuffle()` function is specifically used to randomly permute the elements of an array in-place.

Usage

The `numpy.random.shuffle()` function is used to randomly rearrange elements within an array, which is particularly useful in scenarios like random sampling or data shuffling in machine learning to ensure model robustness.

numpy.random.shuffle(x)

In this syntax, `x` is the array you want to shuffle. The operation is performed in-place, meaning the original array is modified.

Examples

1. Basic Array Shuffling

import numpy as np

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

This example shuffles the elements of the array `[1, 2, 3, 4, 5]` in-place, displaying them in a random order.

2. Shuffling a 2D Array

import numpy as np

arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
np.random.shuffle(arr_2d)
print(arr_2d)

In this example, the rows of the 2D array are shuffled randomly. The order within each row remains unchanged, as `shuffle()` only affects the order along the first axis.

3. Shuffling with Random Seed

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
np.random.seed(42)
np.random.shuffle(arr)
print(arr)

This example uses a random seed to ensure reproducibility, meaning the shuffled order will be the same every time the code is run.

4. Shuffling a 3D Array

import numpy as np

arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])
np.random.shuffle(arr_3d)
print(arr_3d)

In this example, `shuffle()` permutes the 3D array along its first axis. Each sub-array's internal structure stays intact while their order is shuffled.

Tips and Best Practices

  • Use in-place operation wisely. Since `shuffle()` modifies the array in-place, ensure you don't need the original order if it's not stored elsewhere.
  • Set a random seed for reproducibility. Using `np.random.seed()` can help achieve consistent results for debugging or testing.
  • Understand dimensional impact. `shuffle()` affects the order of elements along the first axis (e.g., rows in 2D arrays or sub-arrays in 3D arrays), not the entire array structure.
  • Avoid using on immutable sequences. `shuffle()` is designed for mutable sequences like lists or NumPy arrays, not for tuples or strings.
  • Explore related functions. For non-in-place operations or shuffling along a different axis, consider using `numpy.random.permutation()`.