Home > front end >  Lambda function to display year fraction between today and a date t
Lambda function to display year fraction between today and a date t

Time:09-16

I am trying to apply a lambda function to my DF in order to add a new column. In it, years fraction should be added.

I did try the following :

DF['YEAR_FRAC']  = DF['YEAR_FRAC'].apply(lambda x: datetime.now() - x.DATE_Col/timedelta(days=365))

but this does throw the following error :

KeyError: 'YEAR_FRAC'

and

DF['YEAR_FRAC']  = DF.apply(lambda x: datetime.now() - x.DATE_Col/timedelta(days=365))

throw :

AttributeError: 'Series' object has no attribute 'DATE_Col'

DF looks like :

DATE_Col
2045-02-15 00:00:00
2037-03-15 00:00:00
NaT
2030-02-15 00:00:00

If the error is throw by NaT values, then how do I handle these ?

CodePudding user response:

Try this:

DF['YEAR_FRAC']  = DF['DATE_Col'].apply(lambda x: datetime.now() - x/timedelta(days=365))
  • Related