You can download this code by clicking the button below.
This code is now available for download.
This function takes a pandas DataFrame as input, normalizes the numeric columns using StandardScaler from sklearn, and returns the original DataFrame with the normalized numeric columns concatenated.
Technology Stack : pandas, numpy, sklearn.preprocessing.StandardScaler
Code Type : Function
Code Difficulty : Intermediate
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
def normalize_dataframe(df):
"""
Normalize the numeric columns of a dataframe using StandardScaler from sklearn.
"""
numeric_df = df.select_dtypes(include=[np.number])
scaler = StandardScaler()
scaled_df = pd.DataFrame(scaler.fit_transform(numeric_df), columns=numeric_df.columns)
return pd.concat([df[~df.columns.isin(numeric_df.columns)], scaled_df], axis=1)