Python09
Python09

Reputation: 115

Bucket numbers that fall into specific ranges in python

I want to assign buckets for any numbers that fall under the below categories (0-0.99,1.0-1.99,2.0-2.99 etc,)

However with the below code I receive an error since these are float type. How can I do this alternatively in python?

df.loc[df['Discount Rate'].between(0, 0.99, inclusive=True), 'Discount Rate'] = 'Zero'
df.loc[df['Discount Rate'].between(1.0, 1.99, inclusive=True), 'Discount Rate'] = '1.00-1.99%'
df.loc[df['Discount Rate'].between(2.0, 2.99, inclusive=True), 'Discount Rate'] = '2.00-2.99%'
df.loc[df['Discount Rate'].between(3.0, 3.99, inclusive=True), 'Discount Rate'] = '3.00-3.99%'
df.loc[df['Discount Rate'].between(4.0, 1000, inclusive=True), 'Discount Rate'] = '4.00% or more'
df['Discount Rate']= df['Discount Rate'].replace([np.nan],'N/A')

Upvotes: 0

Views: 668

Answers (1)

BENY
BENY

Reputation: 323316

Check with pd.cut

df['Discount Rate label'] = pd.cut(df['Discount Rate'],
                                   bins = [0,.99,1.99...],
                                   labels = ['Zero', '1.00-1.99%'..])

Upvotes: 2

Related Questions