How to group every 10 % in pandas DataFrame?

Viewed 395

I have data as below.

Date          percent
2021-02-01       22.8
2021-02-01        0.0   
2021-02-02        5.5  
2021-02-03        9.0 
2021-02-04       70.2 
2021-02-04       58.9 
2021-02-06       33.2
2021-02-05       22.5
2021-02-08       12.3
2021-02-09       19.3 

I want to group them in to every 10 %. Desired output is below:

Group   count
<10       333
10-20       6
20-30      32
30-40      23
40-50      47
50-60      10
60-70      54

I've tried with the below code but it didn't give the format I wanted.

df.groupby('percent').count()

Can someone teach me how to make a group per 10 %?

1 Answers

You can use pandas.cut() method in combination with pandas.DataFrame.groupby().

You can bin your data like this:

df = pd.DataFrame({'percent': [22.8, 0.0 , 5.5 , 9.0, 70.2, 58.9, 33.2, 22.5, 12.3, 99.3, 10.0]})
df['binned'] = pd.cut(df['percent'], bins=list(range(0, 101, 10)))

When you group your data on df['binned'] column, it would look like this:

>>> df.groupby('binned').size()
binned
(0, 10]      3
(10, 20]     1
(20, 30]     2
(30, 40]     1
(40, 50]     0
(50, 60]     1
(60, 70]     0
(70, 80]     1
(80, 90]     0
(90, 100]    1
Related