How to create datetime column using date() function on integer array arguments in Python

Viewed 279

my python version is: 3.9.7

I'm trying to create date column from three series of type integer (year, month, day). Each series is an argument to the datetime function date(year,month,day). I am getting errors no matter what I try. I created a simplified example with the same error as the real problem I am trying to solve. If I can find a solution to this simple problem, it will solve the real problem. Thanks. enter image description here

1 Answers

Use to_datetime with DataFrame with columns year, month, day:

year = pd.Series([2001,2003,2001])
month = pd.Series([4,7,5])
day = pd.Series([2,10,23])

s = pd.to_datetime(pd.DataFrame({'year':year, 'month':month, 'day':day})).dt.date
print (s)
0    2001-04-02
1    2003-07-10
2    2001-05-23
dtype: object
   

If need date function (loops solutions, not vectorized):

df1 = pd.DataFrame({'year':year, 'month':month, 'day':day})

s = df1.apply(lambda x: date(x['year'], x['month'], x['day']), axis=1)
print (s)
0    2001-04-02
1    2003-07-10
2    2001-05-23
dtype: object

Or:

s = pd.Series([date(y, m, d) for y, m, d in zip(year, month, day)])
print (s)
0    2001-04-02
1    2003-07-10
2    2001-05-23
dtype: object
Related