NumPy
keyboard_arrow_down 319 guides
chevron_leftNumPy Random Generator
check_circle
Mark as learned thumb_up
1
thumb_down
0
chat_bubble_outline
0
Comment auto_stories Bi-column layout
settings
NumPy Random Generator | shuffle method
schedule Aug 12, 2023
Last updated local_offer
Tags Python●NumPy
tocTable of Contents
expand_more Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!
Start your free 7-days trial now!
NumPy Random's shuffle(~)
method randomly shuffles the NumPy array in-place.
NOTE
To get a new array of shuffled values, use permutation(~)
instead.
Parameters
1. x
| NumPy array
or MutableSequence
The array to shuffle.
2. axis
link | int
| optional
The axis to shuffle. By default, axis=0
.
Return Value
None
- this operation is done in-place.
Examples
Basic usage
Consider the following NumPy array:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
To shuffle this NumPy array:
rng = np.random.default_rng()rng.shuffle(x)x
array([4, 0, 2, 9, 6, 3, 1, 5, 8, 7])
Notice how the shuffle is done in-place.
Setting axis
Consider the following two-dimensional array:
x = np.arange(12).reshape((3,4))x
array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
By default, axis=0
, which means that rows are shuffled:
rng = np.random.default_rng(seed=42)rng.shuffle(x) # axis=0x
array([[ 8, 9, 10, 11], [ 4, 5, 6, 7], [ 0, 1, 2, 3]])
To shuffle the columns, set axis=1
:
rng.shuffle(x, axis=1)x
array([[ 2, 0, 3, 1], [ 6, 4, 7, 5], [10, 8, 11, 9]])
Setting a seed
In order to be able to reproduce the randomness, set a seed like so:
array([5, 6, 0, 7, 3, 2, 4, 9, 1, 8])
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
Official NumPy Documentation
https://numpy.org/doc/stable/reference/random/generated/numpy.random.Generator.shuffle.html
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!