1+ def OneHotEncode (pandas_dataframe ,category_columns = [],check_numerical = False ,max_var = None ):
2+ # Parameter explanation ----
3+ # pandas_dataframe -> The Pandas Dataframe object that contains the column you want to one-hot encode
4+ # category_columns -> List of column names in pandas_dataframe that you want to one-hot encode
5+ # override_alert (Default=False) -> A naive way of checking if the column contains numerical
6+ # data or is unsuitable for one-hot encoding
7+ # Set it to True to turn on the detection
8+
9+ import numpy as numpylib
10+
11+ # The dataframe is copied to a new variable
12+ df = pandas_dataframe .copy ()
13+
14+ # List of list of names of all new columns made for a single column
15+ all_new_cols = []
16+
17+ # List of dictionary of names of all new columns made for a single column
18+ new_col_dict = []
19+
20+ # List of arrays containg the dropped columns that were originally input
21+ dropped_cols = []
22+
23+ numerical_const = 20
24+
25+ for col in category_columns :
26+
27+ # Total number of rows in each column
28+ total_rows = len (df [category_columns [0 ]].values )
29+
30+ category_elements = []
31+ main_row = df [str (col )].values
32+ for category_element in main_row :
33+ category_elements .append (category_element )
34+ category_elements = list (set (category_elements ))
35+
36+ if check_numerical :
37+ if max_var != None :
38+ if len (category_elements ) > max_var :
39+ print (col + ' not suitable for One-Hot Encoding' )
40+ continue
41+ else :
42+ if len (category_elements )> numerical_const :
43+ print (col + ' has more variables than permitted' )
44+ continue
45+
46+ if max_var != None :
47+ if len (category_elements ) > max_var :
48+ print (col + ' has more variables than allowed' )
49+ continue
50+
51+ category_element_dict = {}
52+ for i in range (len (category_elements )):
53+ category_element_dict [category_elements [i ]]= i
54+
55+ category_element_reverse_dict = {}
56+ for i in range (len (category_elements )):
57+ category_element_reverse_dict [col + str (i )]= category_elements [i ]
58+
59+ dict_new_columns = {}
60+
61+ category_element_str = [(col + str (x )) for x in range (len (category_elements ))]
62+ for string in category_element_str :
63+ zero_row = numpylib .zeros ((total_rows ,), dtype = numpylib .int )
64+ dict_new_columns [string ]= zero_row
65+
66+ colnames = []
67+ for i in range (total_rows ):
68+ colnames .append (category_element_str [category_element_dict [main_row [i ]]])
69+ for i in range (total_rows ):
70+ dict_new_columns [colnames [i ]][i ]= 1
71+ for element in category_element_str :
72+ df [element ]= dict_new_columns [element ]
73+
74+ # Original columns are dropped from the dataframe
75+ df = df .drop (col ,1 )
76+
77+ all_new_cols .append (category_element_str )
78+ new_col_dict .append (category_element_reverse_dict )
79+ dropped_cols .append (main_row )
80+
81+ return df ,dropped_cols ,all_new_cols ,new_col_dict
0 commit comments