python - 使用 pandas 将年、月、日列合并为单个日期列

标签 python pandas python-2.7 datetime dataframe

合并数据时我不断遇到错误:

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

我尝试了不同的方法将月份、日期和年份合并到一列中:

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: cannot assemble the datetimes: day is out of range for day

我知道我可以通过使用error='coerce'来强制它,但我不想使用这种方法。

最佳答案

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' 参数。

关于python - 使用 pandas 将年、月、日列合并为单个日期列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52358779/

相关文章:

python - 产品目录 : filter by parameters

Python scrapy,如何在单个蜘蛛中的每个请求之间进行随机延迟?

python - 当半衰期已知时,如何填充药物不规则时间序列的缺失值

python - 处理pandas中的多列和groupby/agg(无需手动分配所有聚合函数)

python - 如何在 python 中评估列表理解以及以什么顺序

python-3.x - python : Add array as new column containing x-previous values for each row

python - 为什么 dict1.items() <= dict2.items() 和 dict1.viewitems() <= dict2.viewitems() 返回不同的结果?

此python3代码的Python2版本用于编码

python-2.7 - 如何防止 ctypes.CDLL ("jvm.dll") 在 Windows Server 2016 上出现 "module not found"错误?

python - 如何使用 nginx + uwsgi 部署 Flask-restplus 应用程序