Show first 10 rows of multi-index pandas dataframe
Here is an answer. Maybe there is a better way to do that (with indexing ?), but I thing it works. The principle seems complex but is quite simple:
- Index the
DataFrame
by year and username. - Group the
DataFrame
by year which is the first level (=0
) of the index - Apply two operations on the sub
DataFrame
obtained by thegroupby
(one for each year)- sort the index by count in ascending order
sort_index(by='count')
-> the row with more counts will be at the tail of theDataFrame
- Only keep the last
top
rows (2 in this case) by using the negative slicing notation ([-top:]
). Thetail
method could also be used (tail(top)
) to improve readability.
- sort the index by count in ascending order
- Dropping the unnecessary level created for year
droplevel(0)
# Test data
df = pd.DataFrame({'year': [2010, 2010, 2010, 2011,2011,2011, 2012, 2012, 2013, 2013, 2014, 2014],
'username': ['b','a','a','c','c','d','e','f','g','i','h','j'],
'count': [400, 505, 678, 677, 505, 505, 677, 505, 677, 505, 677, 505]})
df = df.set_index(['year','username'])
top = 2
df = df.groupby(level=0).apply(lambda df: df.sort_index(by='count')[-top:])
df.index = df.index.droplevel(0)
df
count
year username
2010 a 505
a 678
2011 d 505
c 677
2012 f 505
e 677
2013 i 505
g 677
2014 j 505
h 677