Skip to content
Advertisement

Get Top N items per month in pandas

I have the following dataframe (which is a pretty reduced sample from my original one).

JavaScript

I’m trying to get the top 2 ids for each year AND month. So, for example, the idea was to obtain the below df. My main problem here, is to get the Top n along with the dates, because the nlargest method applies to a pd.Series or a dataframe (but in this case, you cannot pass a list for multiple conditions).

JavaScript

So far, my code is:

JavaScript

Advertisement

Answer

One option is to sort the columns before grouping, and use the nth function:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement