You can download this code by clicking the button below.
This code is now available for download.
This function adds a specified number of random columns to a Pandas DataFrame.
Technology Stack : Pandas, NumPy
Code Type : Pandas DataFrame operation
Code Difficulty : Intermediate
import pandas as pd
import numpy as np
def randomize_dataframe_columns(df, num_new_columns):
"""
Add a specified number of random new columns to the DataFrame.
Parameters:
df (pd.DataFrame): The DataFrame to modify.
num_new_columns (int): The number of new columns to add.
Returns:
pd.DataFrame: The modified DataFrame with additional random columns.
"""
# Generate random data for the new columns
new_columns = pd.DataFrame(np.random.randn(num_new_columns, len(df)), columns=[f'Col_{i}' for i in range(num_new_columns)])
# Concatenate the new columns with the original DataFrame
return pd.concat([df, new_columns], axis=1)