JavaEar 专注于收集分享传播有价值的技术资料

类型错误:" 不支持的操作数类型(一个或多个),用于: - ‘时间戳’和‘STR’" 熊猫 (TypeError: "unsupported operand type(s) for -: 'Timestamp' and 'str'" pandas)

I am working on a project and so far my code looks like this:

def vacation_date(row):
if pd.isnull(row['vacation_date']) == False :
    return float((row['vacation_date'] - row['purchased_trip_date']).days)
else:
    pass 
preprocessed_data['vacation_date'] = data.apply(lambda row:
vacation_date(row), axis=1)

it is returning: TypeError: ("unsupported operand type(s) for -: 'Timestamp' and 'str'", 'occurred at index 3')

I am not sure what I need to do to fix this, any suggestions are appreciated, thanks!

2个回答

    最佳答案

  1. 英文原文

    The error message is one of the clearest I've ever seen in computing - it's telling you that you're trying to subtract a string from a Timestamp. Since what you're subtracting is row['purchased_trip_date'], it means this is a string. Convert it to another Timestamp first.


    中文翻译

    错误信息是我见过在计算最明显的一个 - 它告诉你,你要减去一个时间戳的字符串。既然你是减法是行[" purchased_trip_date" ] 的,这意味着这是一个字符串。将其转换为另一时间戳第一

    The error message is one of the clearest I've ever seen in computing - it's telling you that you're trying to subtract a string from a Timestamp. Since what you're subtracting is row['purchased_trip_date'], it means this is a string. Convert it to another Timestamp first.

    错误信息是我见过在计算最明显的一个 - 它告诉你,你要减去一个时间戳的字符串。既然你是减法是行[" purchased_trip_date" ] 的,这意味着这是一个字符串。将其转换为另一时间戳第一

  2. 参考答案2
  3. how sure are you that every item in data['purchased_trip_date'] and data['vacation_date'] are properly formatted dates? I suspect that one or the other is a string that can't be automagically transformed to a date. The error occurs when Python tries to subtract a timestamp from a string. You should validate the data in those two fields.