Python function error : '<' not supported between types 'str' and 'int'

て烟熏妆下的殇ゞ 提交于 2021-01-29 08:14:13

问题


I am working on repeats classification project. I am calculating time lapse in between a repeat and fresh mail in days. I want to apply a function on this time lapse which states whether it is a fresh mail or repeat mail.

function:

days = df['days_difference']
if(days<30):
   return 'repeat'
else:
   return 'fresh'

I am getting error: not supported between instances of 'str' and 'int'

'days_difference' column contains integer values along with None values.

looking for a solution !


回答1:


That basically means that your 'days ' variable is a string. You can not compare strings with integers using "<". Try :

...
if(int(days)<30):
...



回答2:


One recommendation which you should consider, always perform a search with the exact error you get from python, and often times you get your response within 0.1 ms.

In your case, you are comparing an integer value (let's say 2) to a string value, which happens to be '2') and python does not understand.

You can compare `int(days)' and 30 like:

if(int(day) < 30):
    return 'repeat'
else: 
    return 'fresh'



回答3:


The error is self-explaining :

Python function error : '<' not supported between types 'str' and 'int'

This is caused by a comparison of str and int types, which is invalid in Python 3 (although it's ok in Python 2).

Example :

result = '20' > 10  # In Python 3, this is illegal and will raise an exception

In your case, the error is most probably caused by the test if(days<30):. Your dataframe probably contains str values. You may need to convert them to int before trying to compare to another value:

days = int(df['days_difference'])
if(days<30):
   return 'repeat'
else:
   return 'fresh'


来源:https://stackoverflow.com/questions/53669611/python-function-error-not-supported-between-types-str-and-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!