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

Time:12-07

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

CodePudding user response:

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

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

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

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

df1.apply(lambda x: date(x['year'], x['month'], x['day'], axis=1))

Or:

[date(y, m, d) for y, m, d in zip(year, month, day)]
  • Related