I would like to group out the top results for each element in the index at level 0. For example with this dataframe / series:
import pandas as pd
import numpy as np
np.random.seed(1)
index = list(zip(['A']*5 + ['B']*5, list(range(10))))
df = pd.Series(np.random.random((10)),
index=pd.MultiIndex.from_tuples(index, names=['i0', 'i1']),
name='val')
pd.DataFrame(df)
I would like to keep A
and B
grouped and return the top 3 val
's (descending) from each.
Another similar option here:
(df.sort_values('val', ascending=False).groupby(level=0).head(3)
.sort_index(level = 0, sort_remaining=False, kind="mergesort"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With