groupby and return all rows of first n groups

Viewed 2206

I have a pandas dataframe like below

>>> df.head()
       0      1       2          3   4           5                      6
0  35000  26009  OPTIDX  BANKNIFTY  XX  1499351400  BANKNIFTY1770621000CE
1  35001  26009  OPTIDX  BANKNIFTY  XX  1499351400  BANKNIFTY1770621000PE
2  35002  26000  OPTIDX      NIFTY  XX  1609425000      NIFTY20DEC10400CE
3  35003  26000  OPTIDX      NIFTY  XX  1609425000      NIFTY20DEC10400PE
4  35004  26009  OPTIDX  BANKNIFTY  XX  1499956200  BANKNIFTY1771321100CE

I want to group these in by column 5 in sorted order and return first n groups where n can be given as variable.

I did df.sort_values(5).groupby([5]) i get <pandas.core.groupby.DataFrameGroupBy object at 0x2afc8d0>

How do I get all rows in first 2 groups. In the sample df above group 1 would be 1499351400, group 2 would be 1499351400 group 3 would be 1609425000

Expected output: when groups required =2

       0      1       2          3   4           5                      6
0  35000  26009  OPTIDX  BANKNIFTY  XX  1499351400  BANKNIFTY1770621000CE
1  35001  26009  OPTIDX  BANKNIFTY  XX  1499351400  BANKNIFTY1770621000PE
4  35004  26009  OPTIDX  BANKNIFTY  XX  1499956200  BANKNIFTY1771321100CE

Update1:After trying @jezrael's

>>> k2=k1[k1.groupby(5).ngroup() < 2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/python/2.7/lib/python2.7/site-packages/pandas/core/groupby.py", line 529, in __getattr__
    (type(self).__name__, attr))
AttributeError: 'DataFrameGroupBy' object has no attribute 'ngroup'

Additional: Is it possible to do it without pandas (only python), I may not always find machines with pandas on them. Thanks

2 Answers
Related