NumPy: Shuffle multidimensional array by row only, keep column order unchanged

Learn, how to shuffle multidimensional array by row and only keeping the column order unchanged?
Submitted by Pranit Sharma, on January 19, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

NumPy - Shuffling multidimensional array by row only

A very simple solution for this question is using numpy.random.shuffle(). NumPy's random.shuffle() method modifies a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remain the same.

With this method:

  • if passed an array, it will return a shuffled copy of the array;
    np.random.shuffle() shuffles the array in place
  • if passed an integer, it will return a shuffled range i.e.
    np.random.shuffle(np.arange(n))

Let us understand with the help of an example,

Python code to shuffle multidimensional array by row only

# Import numpy
import numpy as np

# Creating an array
arr = np.arange(10)

# Display original array
print("Original Array:\n",arr,"\n")

# Shuffling array
np.random.shuffle(arr)

# Display result
print("Shuffled array:\n",arr,"\n")

Output

Example: NumPy: Shuffle multidimensional array by row only, keep column order unchanged

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.