How to combine grouping to achieve individual grouping AND combined (summed) counts when group is greater than a number

23 Views Asked by At

I have grouped a dataframe by count. It gives me a group by each value in the column I sepcified.

orig_df.groupby(['count_category'])['number_available'].count().reset_index()

To get example of my current output, use this table:

df = pd.DataFrame({'count_category': ['1','2','3','4','5'],'number_available': ['600','200','100','50','25'],})
count_category number_available
1 600
2 200
3 100
4 50
5 25

What I want is to combine(sum) groups 4 and 5 to get an output like this:

count_category number_available
1 600
2 200
3 100
4+ 75
1

There are 1 best solutions below

0
SoSincere3 On

If I change all of the values that >=4 in the category, before I group, it will give me what I'm looking for. The only thing is that the label is 4 vs 4+, but this is what I was looking for.

orig_df.loc[orig_df['count_category'] >= 4] = 4
orig_df.groupby(['count_category'])['number_available'].count().reset_index()
count_category number_available
1 600
2 200
3 100
4 75