list comprehension vs lambda function in pandas dataframe

Viewed 73

I'm trying to convert decimal years to datetime format in Python. I've managed to make the conversion using a list comprehension, but I cannot get a lambda function working to do the same thing. What am I doing wrong? How can I use a lambda function to make this conversion?

from datetime import datetime, timedelta 
import calendar

df = pd.DataFrame(data = [2021.3, 2021.6], columns = ['dec_date'])

# define a function to convert decimal dates to datetime 
def convert_partial_year(number):

    # round down to get the year
    year = int(number)
    # get the fractional year
    year_fraction = number - year
    # get the number of days in the given year
    days_in_year = (365 + calendar.isleap(year))
    # convert the fractional year into days
    d = timedelta(days=year_fraction * days_in_year)
    # convert the year into a date format
    day_one = datetime(year, 1, 1)
    # add the days into the year onto the date format
    date = d + day_one
    # return the result
    return date

# my lambda function does not work
df.assign(
    date = lambda x: convert_partial_year(x.dec_date)
)

# my list comprehension does work
df.assign(
    date = [convert_partial_year(x) for x in df.dec_date]
)
0 Answers
Related