#NEWLINE# def _categorize( categories , df ) : #NEWLINE# #INDENT# " Categorize columns in dataframe\n\n    >>> df = pd.DataFrame({'x': [1, 2, 3], 'y': [0, 2, 0]})\n    >>> categories = {'y': ['A', 'B', 'c']}\n    >>> _categorize(categories, df)\n       x  y\n    0  1  A\n    1  2  c\n    2  3  A\n\n    >>> _categorize(categories, df.y)\n    0    A\n    1    c\n    2    A\n    dtype: category\n    Categories (3, object): [A, B, c]\n    " #NEWLINE# if ( '.index' in categories ) : #NEWLINE# #INDENT# index = pd . CategoricalIndex ( pd . Categorical . from_codes ( df . index . values , categories [ '.index' ] ) ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# index = df . index #NEWLINE# #UNINDENT# if isinstance ( col , pd . Series ) : #NEWLINE# #INDENT# if ( df . name in categories ) : #NEWLINE# #INDENT# cat = pd . Categorical . from_codes ( df . values , categories [ df . name ] ) #NEWLINE# return pd . Series ( cat , index = index ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# return df #NEWLINE# #UNINDENT# #UNINDENT# else : #NEWLINE# #INDENT# return pd . DataFrame ( dict ( ( ( col , ( pd . Categorical . from_codes ( df [ col ] . values , categories [ col ] ) if ( col in categories ) else df [ col ] . values ) ) for col in df . columns ) ) , columns = df . columns , index = index )