np.random.shuffle()
shuffle mixes up an array's order in place, like shuffling a deck of cards.
In this page:
Syntax
np.random.shuffle(arr) # in place
np.random.shuffle()
np.random.shuffle rearranges the elements of an array along its first axis, in place, and returns None. Use np.random.permutation to get a shuffled copy instead. For 2-D arrays only the rows move, not the values inside rows.
Note:
permutation(10) gives a random ordering of 0 to 9, ideal for train/test splits.
Example: np.random.shuffle()
import numpy as np
np.random.seed(7)
a = np.arange(8)
np.random.shuffle(a)
print(a)
print(np.random.permutation(5))
# Output:
# [2 5 0 6 3 1 4 7]
# [3 4 2 1 0]
Related Topics
Common Mistakes
- Assigning the result of shuffle, which is None
- Expecting columns to shuffle too
- Shuffling when you needed a copy
Chapter Summary
- shuffle changes the array in place
- It returns None
- permutation returns a copy
- Only the first axis is shuffled
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: