将年,月,日列与大 pandas 合并为单个日期列 [英] Combining year, month, day columns into a single date column with pandas

查看:54
本文介绍了将年,月,日列与大 pandas 合并为单个日期列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

合并数据时,我总是遇到错误:

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

我得到的错误:

ValueError:无法组合日期时间:day超出了范围 天

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

我知道我可以通过使用 error ='coerce'来强制执行此操作,但是我想避免使用该方法.

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

推荐答案

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]

如果您要NaTify无效的组合,然后添加errors='coerce'参数.

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

这篇关于将年,月,日列与大 pandas 合并为单个日期列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆