简体   繁体   中英

Make datetime.date column in python from other year,month and day column

Im trying to make a datetime.date type column by combining the year,month and day columns.

This is what i've tried.

        df['date']= date(df['year'],df['month'],df['day'])

It's giving me an error:

TypeError: cannot convert the series to <class 'int'>

I tried parsing by using int() but its giving me the same error.

You can convert it to a string date-time, then use to_datetime to get the series you want. Think x[1] as month, x[0] as day, and x[2] as year.

df = pd.DataFrame([[2,1,2000],[2,3,2003]])
df['new'] = pd.to_datetime(df.apply(lambda x: f"{x[1]}-{x[0]}-{x[2]}", axis=1))

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