This tutorial explains how to use the standard scaler encoding from scikit-learn. This scaler normalizes the data by subtracting the mean and dividing by the standard deviation.

This tutorial will data for flights in and out of NYC in 2013.

Packages

This tutorial uses:

Open up a new Jupyter notebook and import the following:


import statsmodels.api as sm
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import category_encoders as ce

Reading the data

The data is from rdatasets imported using the Python package statsmodels.


df = sm.datasets.get_rdataset('flights', 'nycflights13').data
df.info()


RangeIndex: 336776 entries, 0 to 336775
Data columns (total 19 columns):
 #   Column          Non-Null Count   Dtype  
---  ------          --------------   -----  
 0   year            336776 non-null  int64  
 1   month           336776 non-null  int64  
 2   day             336776 non-null  int64  
 3   dep_time        328521 non-null  float64
 4   sched_dep_time  336776 non-null  int64  
 5   dep_delay       328521 non-null  float64
 6   arr_time        328063 non-null  float64
 7   sched_arr_time  336776 non-null  int64  
 8   arr_delay       327346 non-null  float64
 9   carrier         336776 non-null  object 
 10  flight          336776 non-null  int64  
 11  tailnum         334264 non-null  object 
 12  origin          336776 non-null  object 
 13  dest            336776 non-null  object 
 14  air_time        327346 non-null  float64
 15  distance        336776 non-null  int64  
 16  hour            336776 non-null  int64  
 17  minute          336776 non-null  int64  
 18  time_hour       336776 non-null  object 
dtypes: float64(5), int64(9), object(5)
memory usage: 48.8+ MB

Feature Engineering

Handle null values


df.isnull().sum()

year                 0
month                0
day                  0
dep_time          8255
sched_dep_time       0
dep_delay         8255
arr_time          8713
sched_arr_time       0
arr_delay         9430
carrier              0
flight               0
tailnum           2512
origin               0
dest                 0
air_time          9430
distance             0
hour                 0
minute               0
time_hour            0
dtype: int64

As this model will predict arrival delay, the Null values are caused by flights did were cancelled or diverted. These can be excluded from this analysis.


df.dropna(inplace=True)

Convert the times from floats or ints to hour and minutes


df['arr_hour'] = df.arr_time.apply(lambda x: int(np.floor(x/100)))
df['arr_minute'] = df.arr_time.apply(lambda x: int(x - np.floor(x/100)*100))
df['sched_arr_hour'] = df.sched_arr_time.apply(lambda x: int(np.floor(x/100)))
df['sched_arr_minute'] = df.sched_arr_time.apply(lambda x: int(x - np.floor(x/100)*100))
df['sched_dep_hour'] = df.sched_dep_time.apply(lambda x: int(np.floor(x/100)))
df['sched_dep_minute'] = df.sched_dep_time.apply(lambda x: int(x - np.floor(x/100)*100))
df['flight'] = df.flight.astype(str)
df.rename(columns={'hour': 'dep_hour',
                   'minute': 'dep_minute'}, inplace=True)
                   

Prepare data for modeling

Set up train-test split


target = 'arr_delay'
y = df[target]
X = df.drop(columns=[target, 'time_hour', 'year', 'dep_time', 'sched_dep_time', 'arr_time', 'sched_arr_time', 'dep_delay'])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=1066)
X_train.dtypes

month                 int64
day                   int64
carrier              object
flight               object
tailnum              object
origin               object
dest                 object
air_time            float64
distance              int64
dep_hour              int64
dep_minute            int64
arr_hour              int64
arr_minute            int64
sched_arr_hour        int64
sched_arr_minute      int64
sched_dep_hour        int64
sched_dep_minute      int64
dtype: object

Encode categorical variables

We convert the categorical features to numerical through the leave one out encoder in categorical_encoders. This leaves a single numeric feature in the place of each existing categorical feature. This is needed to apply the scaler to all features in the training data.


encoder = ce.LeaveOneOutEncoder(return_df=True)
X_train_loo = encoder.fit_transform(X_train, y_train)
X_test_loo = encoder.transform(X_test)
X_train_loo.shape

We apply the standard scaler from scikit-learn.


scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train_loo, y_train)
X_train_scaled.shape

X_train_scaled_df = pd.DataFrame(X_train_scaled, columns=X_train.columns)
X_train_scaled_df.describe()

	month	day	carrier	flight	tailnum	origin	dest	air_time	distance	dep_hour	dep_minute	arr_hour	arr_minute	sched_arr_hour	sched_arr_minute	sched_dep_hour	sched_dep_minute
count	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05	2.618760e+05
mean	-1.301713e-16	4.598161e-17	1.415887e-16	-2.153564e-16	6.105726e-17	6.058388e-16	-2.516668e-16	1.274292e-16	8.999015e-17	7.951318e-15	-1.764622e-15	6.009070e-16	-1.608430e-16	-1.117432e-15	-2.422899e-16	7.951318e-15	-1.764622e-15
std	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00	1.000002e+00
min	-1.630540e+00	-1.676892e+00	-3.336721e+00	-5.885651e+00	-7.954211e+00	-8.216296e-01	-4.807096e+00	-1.395737e+00	-1.316373e+00	-1.746525e+00	-1.359586e+00	-2.764704e+00	-1.698053e+00	-3.023737e+00	-1.667935e+00	-1.746525e+00	-1.359586e+00
25%	-7.520552e-01	-8.798827e-01	-8.984300e-01	-6.827688e-01	-6.975891e-01	-8.125293e-01	-8.734769e-01	-7.331093e-01	-7.327537e-01	-8.880329e-01	-9.449566e-01	-6.990625e-01	-8.915001e-01	-8.111693e-01	-8.635545e-01	-8.880329e-01	-9.449566e-01
50%	1.264298e-01	3.098504e-02	1.138961e-01	-1.431278e-01	-4.615378e-02	-6.735426e-01	9.236695e-02	-2.307950e-01	-2.171556e-01	-2.954102e-02	1.434451e-01	5.207997e-02	-2.733634e-02	-6.599369e-03	5.573740e-02	-2.954102e-02	1.434451e-01
75%	1.004915e+00	8.279943e-01	5.012644e-01	5.623605e-01	5.821325e-01	1.336820e+00	6.148843e-01	4.318324e-01	4.644133e-01	8.289509e-01	9.208750e-01	8.032224e-01	8.944383e-01	7.979706e-01	8.601178e-01	8.289509e-01	9.208750e-01
max	1.590571e+00	1.738862e+00	2.408367e+00	1.573161e+01	2.429566e+01	1.337449e+00	7.960190e+00	5.818352e+00	5.353752e+00	2.116689e+00	1.698305e+00	1.742150e+00	1.700991e+00	1.602541e+00	1.721954e+00	2.116689e+00	1.698305e+00

Scale the test set. This can now be passed into the predict or predict_proba functions of a trained model.


X_test_scaled = scaler.transform(X_test_loo)
X_test_scaled_df = pd.DataFrame(X_test_scaled, columns=X_train.columns)
X_test_scaled_df.describe()

	month	day	carrier	flight	tailnum	origin	dest	air_time	distance	dep_hour	dep_minute	arr_hour	arr_minute	sched_arr_hour	sched_arr_minute	sched_dep_hour	sched_dep_minute
count	65470.000000	65470.000000	65470.000000	65470.000000	65470.000000	65470.000000	65470.000000	65470.000000	65470.000000	65470.000000	65470.000000	65470.000000	65470.000000	65470.000000	65470.000000	65470.000000	65470.000000
mean	-0.005041	0.007379	-0.003772	0.001724	0.000449	-0.003078	-0.002807	0.004899	0.005081	0.003615	0.000465	0.001644	-0.002205	0.004651	0.004332	0.003615	0.000465
std	0.997754	0.996867	1.000505	0.993298	0.986614	0.999333	1.010710	1.006461	1.005689	1.002920	1.000407	1.002833	0.999758	1.000658	1.005285	1.002920	1.000407
min	-1.630540	-1.676892	-3.057897	-4.411746	-4.977660	-0.812695	-4.439205	-1.385049	-1.316373	-1.746525	-1.359586	-2.764704	-1.698053	-3.023737	-1.667935	-1.746525	-1.359586
25%	-0.752055	-0.879883	-0.897860	-0.677545	-0.700821	-0.812695	-0.873506	-0.733109	-0.742277	-0.888033	-0.944957	-0.699062	-0.891500	-0.811169	-0.863555	-0.888033	-0.944957
50%	0.126430	0.030985	-0.626442	-0.142877	-0.042937	-0.673640	0.091824	-0.230795	-0.217156	-0.029541	0.143445	0.052080	0.001469	-0.006599	0.055737	-0.029541	0.143445
75%	1.004915	0.827994	0.501080	0.560253	0.577151	1.336826	0.614185	0.442520	0.479378	0.828951	0.920875	0.803222	0.894438	0.797971	0.917574	0.828951	0.920875
max	1.590571	1.738862	2.403800	8.853391	15.483197	1.336826	7.769810	5.722164	5.353752	2.116689	1.698305	1.742150	1.700991	1.602541	1.721954	2.116689	1.698305

No-code/low-code data prep and visualization

Request Demo
Try for Free