def OneHotEncoder(data, keymap=None):
 if (keymap is None):
  keymap = []
  for col in data.T:
   uniques = set(list(col))
   keymap.append(dict(((key, i) for (i, key) in enumerate(uniques))))
 total_pts = data.shape[0]
 outdat = []
 for (i, col) in enumerate(data.T):
  km = keymap[i]
  num_labels = len(km)
  spmat = sparse.lil_matrix((total_pts, num_labels))
  for (j, val) in enumerate(col):
   if (val in km):
    spmat[(j, km[val])] = 1
  outdat.append(spmat)
 outdat = sparse.hstack(outdat).tocsr()
 return (outdat, keymap)

def OneHotEncoder ( data , keymap = None ) : if ( keymap is None ) : keymap = [ ] for col in data . T : uniques = set ( list ( col ) ) keymap . append ( dict ( ( ( key , i ) for ( i , key ) in enumerate ( uniques ) ) ) ) total_pts = data . shape [ 0 ] outdat = [ ] for ( i , col ) in enumerate ( data . T ) : km = keymap [ i ] num_labels = len ( km ) spmat = sparse . lil_matrix ( ( total_pts , num_labels ) ) for ( j , val ) in enumerate ( col ) : if ( val in km ) : spmat [ ( j , km [ val ] ) ] = 1 outdat . append ( spmat ) outdat = sparse . hstack ( outdat ) . tocsr ( ) return ( outdat , keymap )
onehotencoder takes data matrix with categorical columns and converts it to a sparse binary matrix .