I have a pandas multiindex DataFrame and I want to calculate the quantiles of its values ββat a specific index level. This is best explained by example.
First create a DataFrame:
import itertools
import pandas as pd
import numpy as np
item = ('A', 'B')
item_type = (0, 1, 2)
location = range(5)
idx = pd.MultiIndex.from_tuples(list(itertools.product(item, item_type, location)),names=('Item', 'Type', 'Location'))
df = pd.DataFrame(np.random.randn(len(idx), 3), index=idx,columns=('C1', 'C2', 'C3'))
df
Let's say we want to compute a table of median column values ββfor each element and type in all places. This is fairly easy to do using the built-in method:
median_df = df.median(level=[0,1])
median_df
This will create a three-column DataFrame with multiindex = (Item, Type). It works for most common functions like .mean, .max, .min, etc.
But this does not work for .quantile - oddly enough, the quantile has no level parameter.
How can I calculate a given quantile in the same way as for a median, etc.
source
share