Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas.cut doesn't bin zero values

Tags:

python

pandas

I am trying to bin a column into custom categories using a list as suggested in this answer-

bins = [0, 1, 5, 10, 25, 50, 100]
df = DataFrame({'Numbers':[0,1,2,7,11,16,45,200]})
df['Bins'] = pandas.cut(df['Numbers'], bins)
df



    Numbers Bins
0   0       NaN
1   1       (0, 1]
2   2       (1, 5]
3   7       (5, 10]
4   11      (10, 25]
5   16      (10, 25]
6   45      (25, 50]
7   200     NaN

How can I bin:

0 as [0,1] and 200 as (100,...) or >100 category?

like image 566
Sharvari Gc Avatar asked Jan 28 '23 04:01

Sharvari Gc


1 Answers

You should adding np.inf

bins =[-np.inf,1, 5, 10, 25, 50, 100, np.inf]
df['Bins'] = pd.cut(df['Numbers'], bins,include_lowest =True)
df
Out[580]: 
   Numbers          Bins
0        0   (-inf, 1.0]
1        1   (-inf, 1.0]
2        2    (1.0, 5.0]
3        7   (5.0, 10.0]
4       11  (10.0, 25.0]
5       16  (10.0, 25.0]
6       45  (25.0, 50.0]
7      200  (100.0, inf]
like image 96
BENY Avatar answered Jan 31 '23 10:01

BENY