1
$\begingroup$

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.

$\endgroup$
5
$\begingroup$

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"])
$\endgroup$
1
$\begingroup$

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

$\endgroup$
0
$\begingroup$

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

pandas.qcut

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.