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

Python NumPy Programs »



ADVERTISEMENT
ADVERTISEMENT


What's New (MCQs)



Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.