Question: I have a table with the following schema:

```
+-------------------------------------------------------+
|                   table_counter                       |
+----+---------------------+------------+---------------+
| id |      timestamp      | entry_type |    country    |
+----+---------------------+------------+---------------+
+----+---------------------+------------+---------------+
| 10 | 2017-05-01 12:00:00 |    click   |    Germany    |
+----+---------------------+------------+---------------+
| 11 | 2017-05-01 12:00:00 |    view    |    Austria    |
+----+---------------------+------------+---------------+
| 12 | 2017-05-01 12:00:00 |    click   |       UK      |
+----+---------------------+------------+---------------+
| 13 | 2017-05-01 12:00:00 |    view    |      USA      |
+----+---------------------+------------+---------------+

```

I need to return the following result: Select the sum of views and clicks of the top 5 countries by sum of views in the past 30 days.

I know how to count the records all right, but how do I define the constrains? How do I return all entries from five countries with the highest number of `view`s?

Limiting the result to the last 30 days is trivial, but I'm pretty much stuck at the beginning.

Answer: 
It looks like you need `cummax()` instead of `.rolling(N).max()`

```
In [29]: df['new'] = df.groupby('id').value.cummax()

In [30]: df
Out[30]:
   id  value  new
0   1      3    3
1   1      6    6
2   1      3    6
3   2      2    2
4   2      1    2

```

**Timing** (using brand new Pandas version 0.20.1):

```
In [3]: df = pd.concat([df] * 10**4, ignore_index=True)

In [4]: df.shape
Out[4]: (50000, 2)

In [5]: %timeit df.groupby('id').value.apply(lambda x: x.cummax())
100 loops, best of 3: 15.8 ms per loop

In [6]: %timeit df.groupby('id').value.cummax()
100 loops, best of 3: 4.09 ms per loop

```

**NOTE:** [from Pandas 0.20.0 what's new](http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#whatsnew-0200)

* Improved performance of `groupby().cummin()` and `groupby().cummax()` ([GH15048](https://github.com/pandas-dev/pandas/issues/15048), [GH15109](https://github.com/pandas-dev/pandas/issues/15109), [GH15561](https://github.com/pandas-dev/pandas/issues/15561), [GH15635](https://github.com/pandas-dev/pandas/issues/15635))
Using apply will be a tiny bit faster:

```
# Using apply  
df['output'] = df.groupby('id').value.apply(lambda x: x.cummax())
%timeit df['output'] = df.groupby('id').value.apply(lambda x: x.cummax())
1000 loops, best of 3: 1.57 ms per loop

```

Other method:

```
df['output'] = df.groupby('id').value.cummax()
%timeit df['output'] = df.groupby('id').value.cummax()
1000 loops, best of 3: 1.66 ms per loop

```