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]
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