【发布时间】:2022-02-23 21:55:30
【问题描述】:
我正在尝试转换具有真正混合日期格式的列。我已经在 SO 上尝试了一些东西,但仍然没有得到有效的解决方案。我尝试将列更改为“字符串”,还尝试将浮点数转换为 int。
数据
date
1 43076.0
2 43077
3 07 Dec 2017
4 2021-12-22 00:00:00
尝试修复 Excel 日期和“2017 年 12 月 7 日”样式的代码
d = ['43076.0', '43077', '07 Dec 2017', '2021-12-22 00:00:00']
df = pd.DataFrame(d, columns=['date'])
date1 = pd.to_datetime(df['date'], errors='coerce', format='%d %a %Y')
date2 = pd.to_datetime(df['date'], errors='coerce', unit='D', origin='1899-12-30')
frame_clean[col] = date2.fillna(date1)
错误
Name: StartDate, Length: 16189, dtype: object' is not compatible with origin='1899-12-30'; it must be numeric with a unit specified
我喜欢这个解决方案,而不是使用 apply 来降低速度。但我正在努力让它发挥作用。
编辑
分解@FObersteiner 解决方案以便更好地理解。
转换简单日期
df['datetime'] = pd.to_datetime(df['date'], errors='coerce')
0 NaT
1 NaT
2 2018-12-07
3 2021-12-22
隔离数字行
m = pd.to_numeric(df['date'], errors='coerce').notna()
m
0 True
1 True
2 False
3 False
将数字行转换为浮点数
df['date'][m].astype(float)
0 43080.0
1 43077.0
将数字行转换为浮点数,然后转换为 dt 对象
pd.to_datetime(df['date'][m].astype(float), errors='coerce', unit='D', origin='1899-12-30')
0 2017-12-11
1 2017-12-08
将所有内容整合起来并带回简单的日期行
df.loc[m, 'datetime'] = pd.to_datetime(df['date'][m].astype(float), errors='coerce', unit='D', origin='1899-12-30')
print(df)
【问题讨论】:
-
您可以添加一个步骤:在输入为数字的地方定义一个掩码,并将该系列的那一部分分别转换为日期时间(类似于this)。
-
即使在隔离时我仍然会收到该错误。
-
我想你忘了显式转换为浮点数;
.astype(float)