title: Python - Speed up for converting a categorical variable to it's numerical index
body: <p>I need to convert a column of categorical variables in a Pandas data frame into a numerical value that corresponds to the index into an array of the unique categorical variables in the column (long story !) and here's a code snippet that accomplishes that:</p>
  
  <pre><code>import pandas as pd
  import numpy as np
  
  d = {'col': ["baked","beans","baked","baked","beans"]}
  df = pd.DataFrame(data=d)
  uniq_lab = np.unique(df['col'])
  
  for lab in uniq_lab:
      df['col'].replace(lab,np.where(uniq_lab == lab)[0][0].astype(float),inplace=True)
  </code></pre>
  
  <p>which converts the data frame:</p>
  
  <pre><code>    col
   0  baked
   1  beans
   2  baked
   3  baked
   4  beans
  </code></pre>
  
  <p>into the data frame:</p>
  
  <pre><code>    col
   0  0.0
   1  1.0
   2  0.0
   3  0.0
   4  1.0
  </code></pre>
  
  <p>as desired. But my problem is that my dumb little for loop (the only way I've thought of to do this) is slow as molasses when I try to run similar code on big data files. I was just curious as to whether anyone had any thoughts on whether there were any ways to do this more efficiently. Thanks in advance for any thoughts.</p>