import pandas as pd               # pandas for handling mixed data sets 
import numpy as np                # numpy for basic math and matrix operations
from numpy.random import uniform  # numpy for basic math and matrix operations

"""
Explanation: License

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.

Simple target encoding: average-by-level - Pandas and numpy
Imports
End of explanation
"""


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': pd.Series(np.random.choice(1000, 10))})
scratch_df

"""
Explanation: Create a sample data set
End of explanation
"""


# 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:average y 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

"""
Explanation: Encode categorical variables using a rate-by-level approach
End of explanation
"""


# 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:average y 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=-5, high=5))   
        
scratch_df2

"""
Explanation: Perturb to prevent overfitting
End of explanation
"""


