I had a datased that had product, price, category, and county. I used this code to count the number of products per category per county:
df_count = df.groupby(['County','Category']).size().reset_index(name='counts')
My dataframe now looks like this:
| County | Category | counts | |
|---|---|---|---|
| 0 | Blekinge | Accessories & watches | 35 |
| 1 | Blekinge | Audio & video | 101 |
| 2 | Blekinge | Bicycles | 78 |
| 3 | Blekinge | Boat parts & accessories | 65 |
| 4 | Blekinge | Boats | 143 |
| ... | ... | ... | ... |
| 657 | Östergötland | Snowmobile parts & accessories | 2 |
| 658 | Östergötland | Snowmobiles | 5 |
| 659 | Östergötland | Sports & leisure equipment | 335 |
| 660 | Östergötland | Tools | 102 |
| 661 | Östergötland | Trucks & construction | 66 |
662 rows × 3 columns
There are 21 counties and 32 categories. Counts are the number of products in a category. Not all categories are necessary in a county.
I'd like to have a new dataframe with the top N (e.g. 2) largest category of each county and aggregate the remainder into "Others". I want this for each county and it'd look like this:
| County | Category | counts |
|---|---|---|
| Blekinge | Boats | 143 |
| Blekinge | Audio & video | 101 |
| Blekinge | Others | 178 |
| ... | ... | ... |
| Östergötland | Sports & leisure equipment | 335 |
| Östergötland | Tools | 102 |
| Östergötland | Others | 175 |
I've seen previous posts that did similar for arrays
How to group "remaining" results beyond Top N into "Others" with pandas
Sort top N and group 'others' in pandas df
and tried this
# group by & sort descending
df_sorted=df_count.groupby(['County','Category']).sum().sort_values('counts', ascending=False).reset_index()
# rename rows other than top-n to 'Others'
x_sorted.groupby('County').loc[x_sorted.index >=3, 'Category'] = 'Others'
and this
df_count.sort_values(by=['counts'], ascending=False).groupby('County').head(2).sort_values(by=['County']).reset_index(drop=True)
#not_top2 = df.groupby('Version').sum().sort('Value', ascending=False).index[2:]
not_top2 = x.groupby(['County','Category']).sum().sort_values('counts', ascending=False).index[2:]
dfnew = x.replace(not_top2, 'Other')
dfnew.groupby(['County','Category']).sum()
but didn't succeed to get the desired output.
Any help or guidance is very much appreciated!