 Back to blog home

## Groupwise Maximum and Minimum in Python

by Adam on 2012-05-21

﻿When using SQL it's often necessary to get the minimum or maximum for each group in a resultset, and there are straightforward ways to do this.

If, however, you're not using SQL how would you do this?

Below is a full example of how to do this using Python:

``````from datetime import date
from itertools import groupby
import operator

L = [(1,'spam',date(2010,1,1)),(2,'spam',date(2010,1,2)),
(3,'eggs',date(2010,1,2)),(4,'eggs',date(2010,1,1)),
(5,'cheese',date(2010,1,1))]

""" groupwise maximum
sort by date in descending order, then by grouping item
"""
L.sort(key=operator.itemgetter(2), reverse=True)
L.sort(key=operator.itemgetter(1))

for key, group in groupby(L, key=operator.itemgetter(1)):
for item in group:
# first item is tuple with maximum date
print(item)
break
#(5, 'cheese', datetime.date(2010, 1, 1))
#(3, 'eggs', datetime.date(2010, 1, 2))
#(2, 'spam', datetime.date(2010, 1, 2))

""" groupwise minimum
sort by grouping item, and date in ascending order
"""
L.sort(key=operator.itemgetter(1,2))

for key, group in groupby(L, key=operator.itemgetter(1)):
for item in group:
# first item is tuple with minimum date
print(item)
break
#(5, 'cheese', datetime.date(2010, 1, 1))
#(4, 'eggs', datetime.date(2010, 1, 1))
#(1, 'spam', datetime.date(2010, 1, 1))``````

For all of your Python sorting questions, start here: https://wiki.python.org/moin/HowTo/Sorting

tags: python groupwise maximum minimum

Post thanked 0 time(s).

Related posts: