Copyright (C) 2017 J. Patrick Hall, jphall@gwu.edu
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
In [38]:
import pandas as pd # pandas for handling mixed data sets
from numpy.random import uniform # numpy for basic math and matrix operations
In [39]:
scratch_df = pd.DataFrame({'x1': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
'x2': ['C', 'D', 'D', 'D', 'C', 'C', 'E', 'C', 'E', 'E'],
'y': [0, 0, 1, 0, 1, 1, 1, 1, 0, 1]})
scratch_df
Out[39]:
In [44]:
# make a new deep copy of scratch_df
# so you can run this cell many times w/o errors
scratch_df1 = scratch_df.copy()
# loop through columns to create new encoded columns
for col_name in scratch_df.columns[:-1]:
new_col_name = col_name + '_encode'
# create a dictionary of original categorical value:event rate for that value
row_val_dict = {}
for level in scratch_df[col_name].unique():
row_val_dict[level] = scratch_df[scratch_df[col_name] == level]['y'].mean()
# apply the transform from the dictionary on all rows in the column
scratch_df1[new_col_name] = scratch_df[col_name].apply(lambda i: row_val_dict[i])
scratch_df1
Out[44]:
In [41]:
# make a new deep copy of scratch_df
# so you can run this cell many times w/o errors
scratch_df2 = scratch_df.copy()
# loop through columns to create new encoded columns
for col_name in scratch_df.columns[:-1]:
new_col_name = col_name + '_encode'
row_val_dict = {}
# create a dictionary of original categorical value:event rate for that value
for level in scratch_df[col_name].unique():
# apply the transform from the dictionary on all rows in the column
# add in a little random noise, can prevent overfitting for rare levels
row_val_dict[level] = (scratch_df[scratch_df[col_name] == level]['y'].mean())
scratch_df2[new_col_name] = scratch_df[col_name].apply(lambda i: row_val_dict[i] + uniform(low=-0.05, high=0.05))
scratch_df2
Out[41]: