Shuffling DataFrame Columns in Pandas

  • Share this:

Code introduction


This function shuffles the columns of a pandas DataFrame by randomly shuffling the list of column names.


Technology Stack : Pandas, NumPy

Code Type : Pandas DataFrame operation

Code Difficulty : Intermediate


                
                    
import pandas as pd
import numpy as np
import random

def shuffle_dataframe_columns(df, random_seed=None):
    """
    Shuffle the columns of a pandas DataFrame.
    """
    if random_seed is not None:
        np.random.seed(random_seed)
    cols = df.columns.tolist()
    np.random.shuffle(cols)
    return df[cols]                
              
Tags: