【问题标题】:How do I subtract 5 years from a date column to create a new column in python data frame?如何从日期列中减去 5 年以在 python 数据框中创建新列?
【发布时间】:2020-08-19 13:04:29
【问题描述】:

我试过这段代码:

df['ExperienceDate'] = (df['IssueDate']) - relativedelta(years=5)

显示错误:TypeError: unsupported operand type(s) for -: 'DatetimeIndex' and 'relativedelta'

【问题讨论】:

    标签: python dataframe datetime


    【解决方案1】:

    您可以查看a similar question。您不能将 relativedelta 对象与 timedelta 进行比较。而且没有一年这么大的时间增量

    保持相同模块日期时间的解决方案:

    diff=timedelta(days=(5*365)) # convert the number of year into a number of day
    df['ExperienceDate']= df['IssueDate']-diff # then substract
    
    

    结果:

        IssueDate   ExperienceDate
    0   1995-02-01  1990-02-02
    

    【讨论】:

      【解决方案2】:

      成功了

      df['ExperienceDate'] = df['IssueDate'].apply(lambda x:x - relativedelta(years=5))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-29
        • 2020-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-04
        相关资源
        最近更新 更多