Shuffle a given Pandas DataFrame rows

Let us see how to shuffle the rows of a DataFrame. We will be using the sample() method of the pandas module to randomly shuffle DataFrame rows in Pandas.

Example 1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# import the module
import pandas as pd 
    
# create a DataFrame 
data = {'Name': ['Mukul', 'Rohan', 'Mayank'
                 'Shubham', 'Aakash'], 
        'Class': ['BCA', 'BBA', 'BCA', 'MBA', 'BBA'],
        'Location' : ['Saharanpur', 'Meerut', 'Agra'
                      'Saharanpur', 'Meerut']} 
df1 = pd.DataFrame(data) 
    
# print the original DataFrame 
print("Original DataFrame :"
display(df1) 
    
# shuffle the DataFrame rows 
df2 = df1.sample(frac = 1
    
# print the shuffled DataFrame 
print("\nAfter Shuffle:"
display(df2) 

chevron_right


Output :

Example 2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# import the module
import pandas as pd 
    
# create a DataFrame 
ODI_runs = {'name': ['Tendulkar', 'Sangakkara', 'Ponting'
                      'Jayasurya', 'Jayawardene', 'Kohli'
                      'Haq', 'Kallis', 'Ganguly', 'Dravid'], 
            'runs': [18426, 14234, 13704, 13430, 12650
                     11867, 11739, 11579, 11363, 10889]} 
df1 = pd.DataFrame(ODI_runs) 
    
# print the original DataFrame 
print("Original DataFrame :"
display(df1) 
    
# shuffle the DataFrame rows 
df2 = df1.sample(frac = 1
    
# print the shuffled DataFrame 
print("\nAfter Shuffle:"
display(df2) 

chevron_right


Output :

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.