0
0
NumPydata~5 mins

Shuffling arrays in NumPy

Choose your learning style9 modes available
Introduction

Shuffling arrays means mixing up the order of elements randomly. It helps when you want to avoid patterns or biases in data.

When you want to randomize the order of data before training a machine learning model.
When you need to create random samples from a dataset without replacement.
When you want to mix up a list of items to ensure fairness, like shuffling a deck of cards.
When testing algorithms that require random input order to check stability.
When splitting data into random groups or batches.
Syntax
NumPy
import numpy as np

# Create an array
array = np.array([1, 2, 3, 4, 5])

# Shuffle the array in-place
np.random.shuffle(array)

np.random.shuffle() changes the original array order directly (in-place).

It works only on the first axis for multi-dimensional arrays.

Examples
Shuffling an empty array keeps it empty without error.
NumPy
import numpy as np

empty_array = np.array([])
np.random.shuffle(empty_array)
print(empty_array)
Shuffling an array with one element keeps it the same.
NumPy
import numpy as np

single_element_array = np.array([42])
np.random.shuffle(single_element_array)
print(single_element_array)
Shuffling a normal array changes the order randomly.
NumPy
import numpy as np

array = np.array([10, 20, 30, 40, 50])
np.random.shuffle(array)
print(array)
For 2D arrays, shuffle only mixes rows, not elements inside rows.
NumPy
import numpy as np

multi_dim_array = np.array([[1, 2], [3, 4], [5, 6]])
np.random.shuffle(multi_dim_array)
print(multi_dim_array)
Sample Program

This program shows the array before and after shuffling to see the change in order.

NumPy
import numpy as np

# Create an array of numbers 1 to 6
numbers = np.array([1, 2, 3, 4, 5, 6])

print("Before shuffling:", numbers)

# Shuffle the array in-place
np.random.shuffle(numbers)

print("After shuffling:", numbers)
OutputSuccess
Important Notes

Time complexity is O(n), where n is the number of elements.

Space complexity is O(1) because shuffling happens in-place without extra arrays.

Common mistake: expecting np.random.shuffle() to return a new array. It does not; it changes the original array.

Use shuffling when you want to randomize data order. Use sampling if you want random elements without changing the original array.

Summary

Shuffling mixes array elements randomly to remove order bias.

np.random.shuffle() changes the array in-place and works on the first axis for multi-dimensional arrays.

It is useful for preparing data for machine learning and random sampling tasks.