Combining year, month, day columns into a single date column with pandas

Viewed 13047

I keep running into an error when combining my data:

record_id   month   day year   sex
1              7    17  1977    M
2              7    15  1979    M
3              7    26  1978    F
4              7    16  1973    M

I tried different methods of combining the month, date and year into one column:

1. surveys_df['date'] = surveys_df['month'].astype(str) + surveys_df['day'] + surveys_df['year']
2. surveys_df['Date'] = pd.to_datetime(surveys_df[['month', 'day', 'year']])

3. r= pd.to_datetime(surveys_df[['year', 'month', 'day']])

4. surveys_df['date'] = pd.to_datetime(surveys_df[['day','month','year']])

The error I get:

ValueError: cannot assemble the datetimes: day is out of range for day

I know I can force it by using error= 'coerce' but I will like to refrain from using that method.

1 Answers
pd.to_datetime(df[['year', 'month', 'day']])

0   1977-07-17
1   1979-07-15
2   1978-07-26
3   1973-07-16
dtype: datetime64[ns]

If there are invalid combinations you want to NaTify, then add the errors='coerce' argument.

Related