user569685
user569685

Reputation: 191

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.

Upvotes: 0

Views: 225

Answers (1)

Gokturk Sahin
Gokturk Sahin

Reputation: 91

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

Upvotes: 1

Related Questions