Pandas GroupBy
objects are iterables. To extract the last n elements of an iterable, there's generally no need to create a list from the iterable and slice the last n elements. This will be memory-expensive.
Instead, you can use either itertools.islice
(as suggested by @mtraceur) or collections.deque
. Both work in O(n) time.
Unlike a generator, a Pandas GroupBy
object is an iterable which can be reused. Therefore, you can calculate the number of groups via len(g)
for a GroupBy
object g
and then slice g
via islice
. Or, perhaps more idiomatic, you can use GroupBy.ngroups
. Then use pd.concat
to concatenate an iterable of dataframes:
from operator import itemgetter
g = data.groupby(data.index.date, sort=False)
res = pd.concat(islice(map(itemgetter(1), g), max(0, g.ngroups-12), None))
Alternatively, you can use collections.deque
and specify maxlen
, then concatenate as before.
from collections import deque
grouped = data.groupby(data.index.date, sort=False)
res = pd.concat(deque(map(itemgetter(1), grouped), maxlen=12))
As described in the collections
docs:
Once a bounded length deque
is full, when new items are added, a
corresponding number of items are discarded from the opposite end....
They are also useful for tracking transactions and other pools of data
where only the most recent activity is of interest.