title: Converting a pandas Interval into a string (and back again)
body: <p>I'm relatively new to Python and am trying to get some data prepped to train a RandomForest.  For various reasons, we want the data to be discrete, so there are a few continuous variables that need to be discretized.  I found <code>qcut</code> in pandas, which seems to do what I want - I can set a number of bins, and it will discretize the variable into that many bins, trying to keep the counts in each bin even.</p>
  
  <p>However, the output of <code>pandas.qcut</code> is a list of Intervals, and the RandomForest classifier in scikit-learn needs a string.  I found that I can convert an interval into a string by using <code>.astype(str)</code>.  Here's a quick example of what I'm doing:</p>
  
  <pre><code>import pandas as pd
  from random import sample
  
  vals = sample(range(0,100), 100)
  cuts = pd.qcut(vals, q=5)
  str_cuts = pd.qcut(vals, q=5).astype(str)
  </code></pre>
  
  <p>and then str_cuts is one of the variables passed into a random forest.</p>
  
  <p>However, the intent of this system is to train a RandomForest, save it to a file, and then allow someone to load it at a later date and get a classification for a new test instance, that is not available at training time.  And because the classifier was trained on discretized data, the new test instance will need to be discretized before it can be used.  So what I want to be able to do is read in a new instance, apply the already-established discretization scheme to it, convert it to a string, and run it through the random forest.  However, I'm getting hung up on the best way to 'apply the discretization scheme'.</p>
  
  <p>Is there an easy way to handle this?  I assume there's no straight-forward way to convert a string back into an Interval.  I can get the list of all Interval values from the discretization (ex: <code>cuts.unique()</code>) and apply that at test-time, but that would require saving/loading a discretization dictionary alongside the random forest, which seems clunky, and I worry about running into issues trying to recreate a categorical variable (coming mostly from R, which is extremely particular about the format of categorical variables).  Or is there another way around this that I'm not seeing?</p>