2 回答
TA贡献1784条经验 获得超7个赞
无法以相同的方式解析所有日期
加载数据框
如果尚未将该
dates
列转换为 a,则将其转换为 a。str
使用布尔索引选择不同的日期类型
假设常规日期包含
/
假设 Excel 序列日期不包含
/
根据日期时间类型分别修复每个数据帧
将数据帧重新连接在一起。
import pandas as pd
from datetime import datetime
# load data
df = pd.DataFrame({'dates': ['09/01/2020', '05/15/1985', '06/07/2013', '33233', '26299', '29428']})
# display(df)
dates
0 09/01/2020
1 05/15/1985
2 06/07/2013
3 33233
4 26299
5 29428
# set the column type as a str if it isn't already
df.dates = df.dates.astype('str')
# create a date mask based on the string containing a /
date_mask = df.dates.str.contains('/')
# split the dates out for excel
df_excel = df[~date_mask].copy()
# split the regular dates out
df_reg = df[date_mask].copy()
# convert reg dates to datetime
df_reg.dates = pd.to_datetime(df_reg.dates)
# convert excel dates to datetime; the column needs to be cast as ints
df_excel.dates = pd.TimedeltaIndex(df_excel.dates.astype(int), unit='d') + datetime(1900, 1, 1)
# combine the dataframes
df = pd.concat([df_reg, df_excel])
显示(df)
dates
0 2020-09-01
1 1985-05-15
2 2013-06-07
3 1990-12-28
4 1972-01-03
5 1980-07-28
TA贡献2051条经验 获得超10个赞
pd.TimedeltaIndex(dates_in_excel_serial_format, 单位='d') + pd.datetime(1900,1,1)
演示:
> dates_in_excel_serial_format = [29428]
> pd.TimedeltaIndex(dates_in_excel_serial_format, unit='d') + pd.datetime(1900,1,1)
< DatetimeIndex(['1980-07-28'], dtype='datetime64[ns]', freq=None)
添加回答
举报