Skip to content

Commit 17b5fd9

Browse files
haydgouthambs
authored andcommitted
DOC add groupby head and tail to docs
1 parent 57063f9 commit 17b5fd9

File tree

3 files changed

+54
-2
lines changed

3 files changed

+54
-2
lines changed

doc/source/groupby.rst

+32
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,38 @@ can be used as group keys. If so, the order of the levels will be preserved:
707707
708708
data.groupby(factor).mean()
709709
710+
711+
Taking the first rows of each group
712+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
713+
714+
Just like for a DataFrame or Series you can call head and tail on a groupby:
715+
716+
.. ipython:: python
717+
718+
df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])
719+
df
720+
721+
g = df.groupby('A')
722+
g.head(1)
723+
724+
g.tail(1)
725+
726+
This shows the first or last n rows from each group.
727+
728+
.. warning::
729+
730+
Before 0.14.0 this was implemented with a fall-through apply,
731+
so the result would incorrectly respect the as_index flag:
732+
733+
.. code-block:: python
734+
735+
>>> g.head(1): # was equivalent to g.apply(lambda x: x.head(1))
736+
A B
737+
A
738+
1 0 1 2
739+
5 2 5 6
740+
741+
710742
Enumerate group items
711743
~~~~~~~~~~~~~~~~~~~~~
712744

doc/source/v0.14.0.txt

+18
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,24 @@ These are out-of-bounds selections
6161
s.year
6262
s.index.year
6363

64+
- More consistent behaviour for some groupby methods:
65+
- groupby head and tail now act more like filter rather than an aggregation:
66+
67+
.. ipython:: python
68+
69+
df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])
70+
g = df.groupby('A')
71+
g.head(1) # filters DataFrame
72+
73+
g.apply(lambda x: x.head(1)) # used to simply fall-through
74+
75+
- groupby head and tail respect column selection:
76+
77+
.. ipython:: python
78+
79+
g[['B']].head(1)
80+
81+
6482
- Local variable usage has changed in
6583
:func:`pandas.eval`/:meth:`DataFrame.eval`/:meth:`DataFrame.query`
6684
(:issue:`5987`). For the :class:`~pandas.DataFrame` methods, two things have

pandas/core/groupby.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -587,7 +587,8 @@ def head(self, n=5):
587587
"""
588588
Returns first n rows of each group.
589589
590-
Essentially equivalent to ``.apply(lambda x: x.head(n))`` except ignores as_index flag.
590+
Essentially equivalent to ``.apply(lambda x: x.head(n))``,
591+
except ignores as_index flag.
591592
592593
Example
593594
-------
@@ -614,7 +615,8 @@ def tail(self, n=5):
614615
"""
615616
Returns last n rows of each group
616617
617-
Essentially equivalent to ``.apply(lambda x: x.tail(n))``
618+
Essentially equivalent to ``.apply(lambda x: x.tail(n))``,
619+
except ignores as_index flag.
618620
619621
Example
620622
-------

0 commit comments

Comments
 (0)