【问题标题】:Pandas mixed date column with Excel dates, floats, int, string dates - convert to datetimePandas 混合日期列与 Excel 日期、浮点数、int、字符串日期 - 转换为日期时间
【发布时间】: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)

标签: python pandas datetime


【解决方案1】:

对于给定的示例,使用掩码分别转换数字和非数字数据:

import pandas as pd

df = pd.DataFrame({'date':['43076.0', '43077', '07 Dec 2017', '2021-12-22 00:00:00']})

df['datetime'] = pd.to_datetime(df['date'], errors='coerce')

m = pd.to_numeric(df['date'], errors='coerce').notna()
df.loc[m, 'datetime'] = pd.to_datetime(df['date'][m].astype(float), errors='coerce', unit='D', origin='1899-12-30')

print(df)
                  date   datetime
0              43076.0 2017-12-07
1                43077 2017-12-08
2          07 Dec 2017 2017-12-07
3  2021-12-22 00:00:00 2021-12-22

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 2016-05-03
    • 2021-07-14
    • 1970-01-01
    • 2016-01-27
    • 2015-09-17
    相关资源
    最近更新 更多