0

I'm trying to bin some housing price categories in order to overlay them on a map to show neighborhood pricing differences.

When I'm putting this logic together to bin the different housing prices, I get a TypeError of:

TypeError: '<' not supported between instances of 'str' and 'int'

Code is below.

level = []
for i in range(0,len(data_process)):
    if (data_process['HousingCost'][i] < 150000):
        level.append("Low Level Cost")
    elif (data_process['HousingCost'][i] >= 150001 and data_process['HousingCost'][i] < 300000):
        level.append("Mid-1 Level Cost")
    elif (data_process['HousingCost'][i] >= 300001 and data_process['HousingCost'][i] < 450000):
        level.append("Mid-2 Level Cost")
    elif (data_process['HousingCost'][i] >= 450001 and data_process['HousingCost'][i] < 600000):
        level.append("High-1 Level Cost")
    else:
        level.append("High-2 Level Cost")   

data_process['Level_labels'] = level
data_process.head()

I'm unsure why I'm getting this type error as I think I've structured things correctly.

Can I please have some assistance in correcting this TypeError?

Thank you!

Jeff
  • 1
  • 1
  • 4
  • Does this answer your question? [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers) – andreis11 May 02 '20 at 17:12

1 Answers1

0

The error occurs because you are trying to compare string value with int, probably because the values accessed inside data_process are strings.

Try to convert data_process accessed values to int. For example:

level = []
for i in range(0,len(data_process)):
    housing_cost = int(data_process['HousingCost'][i])
    if housing_cost < 150000:
        level.append("Low Level Cost")
    elif housing_cost >= 150001 and housing_cost < 300000:
        level.append("Mid-1 Level Cost")
    elif housing_cost >= 300001 and housing_cost < 450000:
        level.append("Mid-2 Level Cost")
    elif housing_cost >= 450001 and housing_cost < 600000:
        level.append("High-1 Level Cost")
    else:
        level.append("High-2 Level Cost")   
Gabio
  • 9,126
  • 3
  • 12
  • 32
  • It may have because I was directed to another error: ValueError: invalid literal for int() with base 10: '$101,990'. I think I need to change the format of my housing values so it reads it as a literal int. – Jeff May 02 '20 at 17:18
  • you can replace the commas and the `$` and only then convert to int. Try: `int(data_process['HousingCost'][i].replace('$','').replace(',',''))` – Gabio May 02 '20 at 17:22