Suppose I have pandas DataFrame like this: which looks like: I want to get a new DataFrame with top 2 records for each id, like this: I can do it with numbering records within group after groupby: which looks like: then for the desired output: Output: But is there more effective/elegant approach to do this? And also is there more
Tag: greatest-n-per-group
Django Query That Get Most Recent Objects From Different Categories
I have two models A and B. All B objects have a foreign key to an A object. Given a set of A objects, is there anyway to use the ORM to get a set of B objects containing the most recent object created for each A object. Here’s an simplified example: So I’m looking for a query that returns