Pandas: Why do I need to do apply lambda instead of nesting functions?

Viewed 54

In order to convert this string column to datetime with the year, month and day I'm doing this:

df['date_ymd'] = df['date'].apply(lambda x: pd.to_datetime(x.strftime('%Y-%m-%d')))

However, looking at the way this code has one function nested in another, and also coming from an r programming background, I would expect this, more parsimonious approach to work:

df['date_ymd'] = pd.to_datetime(df['date'].strftime('%Y-%m-%d'))

But this returns the error:

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

Can anyone explain why this is not possible?

Thanks!

Edited: Here's an example of my data:

df = pd.DataFrame(
           {"date" : [None, '2020-06-13 17:32:55.367081+02:00', '2020-03-26 14:33:26.506618+01:00']},
         index = [1, 2, 3])
1 Answers

You are getting the error because the object is Series. Instead, you can do it in this way by adding .dt before .strftime() to get .dt type:

df = pd.DataFrame(
       {"date" : [None, '2020-06-13 17:32:55.367081+02:00', '2020-03-26 14:33:26.506618+01:00']},
     index = [1, 2, 3])
df['date_ymd'] = pd.to_datetime(df['date'], utc = True).dt.strftime('%Y-%m-%d')

Output:

                               date    date_ymd
1                              None         NaN
2  2020-06-13 17:32:55.367081+02:00  2020-06-13
3  2020-03-26 14:33:26.506618+01:00  2020-03-26
Related