Skip to content

Commit 83f3c96

Browse files
committed
Merge pull request #8724 from unutbu/groupmax-recipe
DOC: Select row with maximum value from each group
2 parents 1382aa3 + e9c5d25 commit 83f3c96

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

doc/source/cookbook.rst

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,19 @@ Unlike agg, apply's callable is passed a sub-DataFrame which gives you access to
588588
df['beyer_shifted'] = df.groupby(level=0)['beyer'].shift(1)
589589
df
590590
591+
`Select row with maximum value from each group
592+
<http://stackoverflow.com/q/26701849/190597>`__
593+
594+
.. ipython:: python
595+
596+
df = pd.DataFrame({'host':['other','other','that','this','this'],
597+
'service':['mail','web','mail','mail','web'],
598+
'no':[1, 2, 1, 2, 1]}).set_index(['host', 'service'])
599+
mask = df.groupby(level=0).agg('idxmax')
600+
df_count = df.loc[mask['no']].reset_index()
601+
df_count
602+
603+
591604
Expanding Data
592605
**************
593606

@@ -1202,4 +1215,4 @@ of the data values:
12021215
{'height': [60, 70],
12031216
'weight': [100, 140, 180],
12041217
'sex': ['Male', 'Female']})
1205-
df
1218+
df

0 commit comments

Comments
 (0)