Title: Get first two rows from first two groups
Tags: python;pandas;pandas-groupby
Question: Consider the data frame df
mux = pd.MultiIndex.from_arrays([
list('aaaabbbbbccdddddd'),
list('tuvwlmnopxyfghijk')
], names=['one', 'two'])
df = pd.DataFrame({'col': np.arange(len(mux))}, mux)
col
one two
a   t      0
u      1
v      2
w      3
b   l      4
m      5
n      6
o      7
p      8
c   x      9
y     10
d   f     11
g     12
h     13
i     14
j     15
k     16
How do I elegantly get the first two rows of the first two groups if I group by the first level of the index:
col
one two
a   t      0
u      1
b   l      4
m      5

Here is the accepted answer: Option 1
You could use a list comp and pd.concat:
pd.concat([g.head(2) for _, g in df.groupby(level=0)][:2])
col
one two
a   t      0
u      1
b   l      4
m      5
Since having the list comp complete is an unnecessary overhead, you could use itertools.takewhile to prevent that.
it = itertools.takewhile(lambda x: x[0] < 2, enumerate(df.groupby(level=0)))
pd.concat([g.head(2) for _, (_, g) in it])
col
one two
a   t      0
u      1
b   l      4
m      5
Option 2
Another possible solution I could think of is pre-filtering your df to retain rows for only the first two values of index level 0, and then do the groupby.
# https://stackoverflow.com/a/46900625/4909087
df.loc[df.index.levels[0][:2].values].groupby(level=0).head(2)
col
one two
a   t      0
u      1
b   l      4
m      5
Comment for this answer: @piRSquared Just got an option 2.
Comment for this answer: Your comprehension fully completes.  I wonder if there is a way to break it early.

Here is another answer: Looks hacky but this is what I tried
df.groupby(level=['one']).head(2)[:4]
col
one two
a   t   0
b   l   4
Comment for this answer: Certainly, but cleaner than the list comp!

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:10/24/17', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><pandas><pandas-groupby>', 'Title': 'Get first two rows from first two groups', 'ViewCount': 52, 'id': 46900357, 'user_AboutMe': '<p>Finance professional turned python/pandas enthusiast.</p>\n<h2>Canonicals</h2>\n<ul>\n<li>How to Pivot a Pandas DataFrame <a href="https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe">Q</a>|<a href="https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe/47152692#47152692">A</a></li>\n<li>Pandas concat <a href="https://stackoverflow.com/questions/49620538/what-are-the-levels-keys-and-names-arguments-for-in-pandas-concat-functio">Q</a>|<a href="https://stackoverflow.com/questions/49620538/what-are-the-levels-keys-and-names-arguments-for-in-pandas-concat-functio/49620539#49620539">A</a></li>\n<li>Operate with a Series on every column of a DataFrame <a href="https://stackoverflow.com/q/53217607/2336654">Q</a>|<a href="https://stackoverflow.com/a/53217608/2336654">A</a></li>\n<li>How Does Numpy\'s <code>axis</code> argument work with <code>sum</code> <a href="https://stackoverflow.com/a/40859008/2336654">A</a></li>\n</ul>\n<p><strong>Support</strong><br />\nIf you\'ve found my questions and/or answers helpful, feel free to show your support or appreciation by up-voting.</p>\n<p>If you are looking for more of my content, you can explore below or visit a few of my selected answers.</p>\n<p><a href="https://stackoverflow.com/a/46192213/2336654" title="Perform inline column renaming with a list and without altering original dataframe">Renaming Columns Via Pipeline</a><br />\n<a href="https://stackoverflow.com/a/46165056/2336654," title="Focus on simple adjustment to speed things up as well as providing some other ideas">Selecting Rows From a DataFrame</a></p>\n<h3>Editorial</h3>\n<ul>\n<li><a href="http://stackoverflow.com/a/38466059/2336654">How to write a good question</a></li>\n</ul>\n<h3>Underrated</h3>\n<ul>\n<li><a href="https://stackoverflow.com/a/57014212/2336654">https://stackoverflow.com/a/57014212/2336654</a></li>\n</ul>\n<p>#SOreadytohelp</p>\n', 'user_AccountId': 2707337.0, 'user_DisplayName': 'piRSquared', 'user_Reputation': 271801.0, 'user_Views': 20314.0, 'user_id': 2336654.0}}