简体   繁体   中英

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

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. 在此处输入图像描述

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM