Shuffling of rows means changing the sequence of rows randomly. Pandas allow us to shuffle the order or rows using the sample() method. We will be using the sample() method to randomly shuffle the order of rows in pandas DataFrame.
pandas.DataFrame.sample() Method
The sample() method is an inbuilt method for shuffling sequences in python. Hence, in order to shuffle the rows in DataFrame, we will use DataFrame.sample() method. Shuffle method takes a sequence (list) as an input and it reorganize the order of that particular sequence.
Syntax:
DataFrame.sample(
n=None,
frac=None,
replace=False,
weights=None,
random_state=None,
axis=None,
ignore_index=False
)
# or
DataFrame.sample(n=none, frac=none, axis= none)
Parameters:
- n: n is total number of rows to be shuffled.
- frac: frac is fraction of total instances needs to be returned, i.e., number of times shuffling needs to be done.
- axis: '0' or 'row' for rows and '1' or 'column' for columns.
Note: The sample() method does not work with immutable types of data types like strings.
To work with Python Pandas, we need to import the pandas library. Below is the syntax,
import pandas as pd
Example:
Output:

need an explanation for this answer? contact us directly to get an explanation for this answer