w3resource

NumPy: Shuffle specific rows of a given array


Shuffle specific rows in a 11x3 student data array.

Write a NumPy program to create a 11x3 array filled with student information (id, class and name) and shuffle the said array rows starting from 3rd to 9th.

Sample Solution:

Python Code:

# Importing NumPy library
import numpy as np

# Setting seed for reproducibility
np.random.seed(42) 

# Creating a NumPy array containing student data
student = np.array([
    ['stident_id', 'Class', 'Name'],
    ['01', 'V', 'Debby Pramod'],
    ['02', 'V', 'Artemiy Ellie'],
    ['03', 'V', 'Baptist Kamal'],
    ['04', 'V', 'Lavanya Davide'],
    ['05', 'V', 'Fulton Antwan'],
    ['06', 'V', 'Euanthe Sandeep'],
    ['07', 'V', 'Endzela Sanda'],
    ['08', 'V', 'Victoire Waman'],
    ['09', 'V', 'Briar Nur'],
    ['10', 'V', 'Rose Lykos']
])

# Displaying the original array
print("Original array:")
print(student)

# Shuffling rows from index 2 to 7 (3rd to 8th rows)
np.random.shuffle(student[2:8])

# Displaying the shuffled array
print("Shuffle the said array rows starting from 3rd to 9th")
print(student) 

Sample Output:

Original array:
[['stident_id' 'Class' 'Name']
 ['01' 'V' 'Debby Pramod']
 ['02' 'V' 'Artemiy Ellie']
 ['03' 'V' 'Baptist Kamal']
 ['04' 'V' 'Lavanya Davide']
 ['05' 'V' 'Fulton Antwan']
 ['06' 'V' 'Euanthe Sandeep']
 ['07' 'V' 'Endzela Sanda']
 ['08' 'V' 'Victoire Waman']
 ['09' 'V' 'Briar Nur']
 ['10' 'V' 'Rose Lykos']]
Shuffle the said array rows starting from 3rd to 9th
[['stident_id' 'Class' 'Name']
 ['01' 'V' 'Debby Pramod']
 ['02' 'V' 'Artemiy Ellie']
 ['03' 'V' 'Baptist Kamal']
 ['07' 'V' 'Endzela Sanda']
 ['04' 'V' 'Lavanya Davide']
 ['06' 'V' 'Euanthe Sandeep']
 ['05' 'V' 'Fulton Antwan']
 ['08' 'V' 'Victoire Waman']
 ['09' 'V' 'Briar Nur']
 ['10' 'V' 'Rose Lykos']]

For more Practice: Solve these Related Problems:

  • Write a NumPy program to randomly shuffle a subset of rows in a 2D array using np.random.shuffle on a view.
  • Create a function that accepts start and end indices to shuffle only that block of rows while leaving other rows intact.
  • Implement a solution using advanced indexing to extract, shuffle, and then reinsert the specified rows into the original array.
  • Test the row-shuffling function on an array with mixed data types (e.g., strings and numbers) to ensure the integrity of the data is maintained.

Go to:


PREV : Compute element-wise arithmetic mean of two arrays.
NEXT : Extract rows based on column starting character.


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.