# Continuous variable to categorical by quartiles?

Let's stay I have a field with a continuous variable, like a count of people waiting in line. I want to take those values and create a categorical value based on quartiles. Let's say my range of values is 1 to 80 and the quartiles tell me that a "very short" line is less than 5 people, a "short" line in 6 to 30, a "long" line is 31 to 50 and a "very long" line is >=51

I can think of different ways to write this in python/pandas/numpy but something tell me that one of you can come up with a method/snippet that is short and elegant. Note that I want the method to also generate the quartile values, something that I haven't really done in Python before.

Panda's Categorical Data Type is designed for that type of analysis, pandas.cut can divide by user-defined bins and pandas.qcut can create quantile-based discretization. Something like this:

import numpy as np
import pandas as pd

df = pd.DataFrame({'value': np.random.randint(1, 80, 20)})
df['group'] = pd.cut(df.value,
bins=[0, 5, 31, 51, 80],
labels=["very short", "short", "long", "very long"])


Unless I misunderstood you completely, I think mquantiles in scipy.stats easily does what you want.

I might come a little late but I think this is what you are looking for:

pandas.qcut