Shuffle an array with python, randomize array item order with python
To mix up or shuffle an array in Python use the built-in random.shuffle()
function. The beauty of this function is it performs the shuffle in-place:
This quick and dirty in-place shuffling method is efficient for memory since it does not make additional copies of the array!
Shuffling the immutable (becoming mutable)
If you are dealing with data that should remain unchanged (immutable) or if the original array needs to survive the shuffle unscathed, Python's got your back with random.sample()
:
This move gives you a new, shuffled copy of the original array, keeping the original array as safe as a bear in a bulletproof vest!
Sklearn shuffle: The consistent comrade
When dealing with related arrays (like in machine learning scenarios), it's crucial to shuffle these arrays together. Pair programming? Try pair shuffling with sklearn.utils.shuffle
:
Setting a random_state
ensures repeatable randomness, crucial for consistency in experiments or testing.
Tailor-made shuffles
Need more control over your shuffles? Want to tell Python how exactly to shuffle your array? Custom shuffling function to the rescue:
This flexibility allows you to implement any algorithm of your choice for array shuffling.
Alternatives and special scenarios
Depending on your data and use case, different shuffling methods might be more suitable:
ND-array shuffling using NumPy
For dealing with large multi-dimensional arrays, np.random.shuffle
can do the job efficiently:
Pandas DataFrame shuffling
Tabular data can be shuffled within a pandas DataFrame using DataFrame.sample
:
Note: frac
is the fraction of rows to return in the shuffled array. Setting frac=1
tells pandas to use all rows.
Secure shuffling with secrets
In a security-sensitive context, secrets
module provides better randomness:
Was this article helpful?