简体   繁体   中英

pandas.cut doesn't bin zero values

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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM