Q:

python dataframe latest x rows of each entry in a column

Need to select the latest x purchases of every client.
Is there a performant way to select the latest x rows for every client? Say we have a dataframe which looks like this:
df1 = 
Client Product ID
A      1       330
B      1       15
A      5       329
A      3       328
A      2       327
B      6       14
A      7       326
A      7       325
C      9       205
C      3       204
C      2       203
C      1       202
C      1       201
B      2       13
B      2       12
B      2       11

were ID is just an incremental id (meaning the id gives you the number of the purchase that the client has made) and we want to select the last two purchases for every client so that the output would look like this:
df2=
Client Product ID
A      1       330
A      5       329
B      1       15
B      6       14
C      9       205
C      3       204

is it possible to do this without looping through the dataframe?

A:

Sort the dataframe by ID in descending order, group by Client and "pick" the first 2 rows of each group.
df1.sort_values('ID', ascending=False).groupby('Client').head(2)

Client  Product   ID
     A        1  330
     A        5  329
     C        9  205
     C        3  204
     B        1   15
     B        6   14

