Subtract an year from a datetime column in pandas

前端 未结 3 591
难免孤独
难免孤独 2020-11-29 10:18

I have a datetime column as below -

>>> df[\'ACC_DATE\'].head(2)
538   2006-04-07
550   2006-04-12
Name: ACC_DATE, dtype: datetime64[ns]


        
相关标签:
3条回答
  • 2020-11-29 10:28

    You can use DateOffset to achieve this:

    In[88]:
    df['NEW_DATE'] = df['ACC_DATE'] - pd.DateOffset(years=1)
    df
    
    Out[88]: 
            ACC_DATE   NEW_DATE
    index                      
    538   2006-04-07 2005-04-07
    550   2006-04-12 2005-04-12
    
    0 讨论(0)
  • 2020-11-29 10:32

    You could use pd.Timedelta:

    df["NEW_DATE"] = df["ACC_DATE"] - pd.Timedelta(days=365) 
    

    Or replace:

    df["NEW_DATE"] = df["ACC_DATE"].apply(lambda x: x.replace(year=x.year - 1))
    

    But neither will catch leap years so you could use dateutil.relativedelta :

    from dateutil.relativedelta import  relativedelta
    
    df["NEW_DATE"] = df["ACC_DATE"].apply(lambda x: x - relativedelta(years=1))
    
    0 讨论(0)
  • 2020-11-29 10:34

    Use DateOffset:

    df["NEW_DATE"] = df["ACC_DATE"] - pd.offsets.DateOffset(years=1)
    print (df)
            ACC_DATE   NEW_DATE
    index                      
    538   2006-04-07 2005-04-07
    550   2006-04-12 2005-04-12
    
    0 讨论(0)
提交回复
热议问题