def _recode(x, levels):
 from pandas import Series
 name = None
 if isinstance(x, Series):
  name = x.name
  x = x.values
 if (x.dtype.type not in [np.str_, np.object_]):
  raise ValueError('This is not a categorial factor. Array of str type required.')
 elif (not isinstance(levels, dict)):
  raise ValueError('This is not a valid value for levels. Dict required.')
 elif (not (np.unique(x) == np.unique(list(iterkeys(levels)))).all()):
  raise ValueError('The levels do not match the array values.')
 else:
  out = np.empty(x.shape[0], dtype=np.int)
  for (level, coding) in iteritems(levels):
   out[(x == level)] = coding
  if name:
   out = Series(out)
   out.name = name
  return out

def _recode ( x , levels ) : from pandas import Series name = None if isinstance ( x , Series ) : name = x . name x = x . values if ( x . dtype . type not in [ np . str_ , np . object_ ] ) : raise ValueError ( 'This is not a categorial factor. Array of str type required.' ) elif ( not isinstance ( levels , dict ) ) : raise ValueError ( 'This is not a valid value for levels. Dict required.' ) elif ( not ( np . unique ( x ) == np . unique ( list ( iterkeys ( levels ) ) ) ) . all ( ) ) : raise ValueError ( 'The levels do not match the array values.' ) else : out = np . empty ( x . shape [ 0 ] , dtype = np . int ) for ( level , coding ) in iteritems ( levels ) : out [ ( x == level ) ] = coding if name : out = Series ( out ) out . name = name return out
recode categorial data to int factor .