I would like to groupby my pandas dataframe based on a given range condition. For example:
Number, Amount
1, 5
2, 10
3, 11
4, 3
5, 5
6, 8
7, 9
8, 6
Range conditions:
1 till 4 (included), named A: 5+10+11+3 = 29
5 and higher, named B: 5+8+9+6 = 28
Desired outcome:
Number, Amount
A, 29
B, 28
EDIT: Thanks for the great solutions. I would like to be able to add more range conditions if needed, so 5-7 and 8 alone should also be a possibility. Is it possible to keep that flexible?
You can use pd.cut
also, helpful if you more that two labels and ranges:
df.groupby(pd.cut(df['Number'],
bins=[0,4,np.inf],
labels=['A', 'B']))['Amount'].sum().reset_index()
Output:
Number Amount
0 A 29
1 B 28
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With