Python Pandas: TypeError: unsupported operand type(s) for +: 'datetime.time' and 'Timedelta'

后端 未结 2 2022
南旧
南旧 2020-12-29 15:11

I am attempting to add two series in a dataframe in pandas with the first series being a 24-hr time value (e.g. 17:30) exported from an excel file and the second series bein

相关标签:
2条回答
  • 2020-12-29 15:46

    The cause

    The error is pretty clear. If you check the types of the elements, you will find out that at some point you are tying to add datetime.time object and pandas.Timedelta.

    There are 2 kinds of dates, times and timedeltas:

    • python's builtin from datetime module i.e. datetime.time, datetime.date, datetime.timedelta, ...
    • pandas / numpy i.e pandas.Timestamp, pandas.Timedelta

    these two stacks are incompatible for basic operations as addition or comparison.

    Solution 1

    Convert everything to pandas type and extract the times in the end

    You should make sure, that dtypes of your columns are something like datetime64[ns] and timedelta64[ns]. For that, try converting them explicitly using pd.to_datetime and pd.to_timedelta.

    Solution 2

    Another approach would be just converting the Delta column to datetime.timedelta you could try

    df["end_Time"] = df["Start_Time"] + df["Delta"].map(pd.Timedelta.to_pytimedelta)
    

    But you may run into some more errors depending on what is in your df["Delta"] and df["Start_Time"]

    0 讨论(0)
  • 2020-12-29 15:47

    Try this:

    import datetime as dt
    
    df["end_Time"] = df["Start_Time"] + df["Delta"].map(dt.timedelta)
    
    0 讨论(0)
提交回复
热议问题