Home »
Python »
Python Programs
Shuffling/Permutating a DataFrame in pandas
Learn, how to shuffle/Permutate dataframe in Python pandas?
By Pranit Sharma Last updated : October 06, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
Problem statement
Suppose that we are given a pandas DataFrame and we need to shuffle this dataframe either by rows or by columns.
Shuffling/Permutating a pandas dataframe
For this purpose, we will use numpy random.permutation() which randomly permutes a sequence, or return a permuted range.
We will permute this dataframe row-wise and pass the dataframe indices as an argument in the permutation method.
Let us understand with the help of an example,
Python program to shuffle/Permutate dataframe in pandas
# Importing pandas package
import pandas as pd
# Import numpy
import numpy as np
# Creating a DataFrame
df = pd.DataFrame({'A':range(10), 'B':range(10)})
# Display DataFrame
print("Original DataFrame:\n",df,"\n")
# Shuffling dataframe
res = df.reindex(np.random.permutation(df.index))
# Display result
print("Result:\n",res)
Output
The output of the above program is:
Python Pandas Programs »