Homesand
Homesand

Reputation: 423

Groupby Pandas with customized range?

I have a DataFrame:

 ID       Value
  1           1  
  2           2
  3           1    
  4           1
  5           2
  6           3
  7           4
  8           5  
  9          10  
 10          15

I want to groupby by my value and count the ID, in the customized range: <=2, 3-9, >= 10

The results would look like:

 Value      ID
 <=2         5
 3-9         3
 >= 10       2

Upvotes: 1

Views: 89

Answers (2)

Pyd
Pyd

Reputation: 6159

I don't think you need groupby.

labels = ['<=2', '3-9', '>=10']
bins = [0,2,9, np.inf]
pd.cut(df['Value'],bins=bins,labels=labels).value_counts().reset_index()
#out[]
index   Value
<=2     5
3-9     3
>=10    2

Upvotes: 2

Abhi
Abhi

Reputation: 4233

Use pd.cut and groupby

import numpy as np

labels = ['<=2', '3-9', '>=10']
bins = [0,2,9, np.inf]

df.groupby(pd.cut(df['Value'], bins, labels=labels)).size().to_frame('ID')

# Output

         ID
Value   
 <= 2     5
  3-9     3
 >=10     2

Upvotes: 3

Related Questions