pandas 类型错误:“不支持 - 的操作数类型:'时间戳'和'str'”熊猫

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43123029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:18:40  来源:igfitidea点击:

TypeError: "unsupported operand type(s) for -: 'Timestamp' and 'str'" pandas

pythonpandastypeerror

提问by kwashington122

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')

它正在返回:TypeError: (“不支持的操作数类型-:'时间戳'和'str'”,'发生在索引3')

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

我不确定我需要做什么来解决这个问题,任何建议表示赞赏,谢谢!

采纳答案by Mark Ransom

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 Timestampfirst.

错误消息是我在计算中见过的最清晰的消息之一——它告诉你你正试图从时间戳中减去一个字符串。由于您减去的是row['purchased_trip_date'],这意味着这是一个字符串。Timestamp先把它转换成另一个。

回答by JD Long

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.

如何确保你在每一个项目data['purchased_trip_date']data['vacation_date']格式正确的日期?我怀疑其中一个是无法自动转换为日期的字符串。当 Python 尝试从字符串中减去时间戳时会发生该错误。您应该验证这两个字段中的数据。