Home > Enterprise >  Range of int as keys for dict
Range of int as keys for dict

Time:07-04

I have a column which rejected amounts (these are just 5 exmaples)

enter image description here

I want to add a column, given points based on the price.

For example, if price is betwen 0 and 100 -> 0.

what i did was :

dict_reject_amount = {0:0,\
                      range(1,101):1,\
                      range(101,201):2,\
                      range(201,301):3,\
                      range(301,401):4,\
                      range(401,501):5,\
                      range(501,601):6,\
                      range(601,701):7,\
                      range(701,801):8,\
                      range(801,901):9,\
                      range(901,100000):9}

convert to int, floats do not matter

new['rejected_int'] = new['rejected'].astype(int)
new['reject_amount_points']= new['rejected_int'].map(dict_reject_amount)

enter image description here

Unfortunately it didn't work.

CodePudding user response:

You can use replace to apply the dict values

new['reject_amount_points'] = df['rejected_int'].replace(dict_reject_amount)

CodePudding user response:

An int isn't equal to a range, and when you do a dictionary lookup, it's testing for equality, not membership.

I think the easiest solution is to convert your points calculation into a mathematical function:

>>> rejected_int = [228, 1063, 121, 1409, 1428]
>>> [min((n   99) // 100, 9) for n in rejected_int]
[3, 9, 2, 9, 9]
  • Related