Pandas read_excel:正确解析 Excel 日期时间字段

问题描述

我将以下示例数据存储在 Excel 文件

索赔 CODE1 年龄 日期
7538 359 71 28/11/2019
7538 359 71 28/11/2019
540 428 73 16/10/2019
540 428 73 16/10/2019
605 1670 40 04/12/2019
740 134 55 24/12/2019

使用 pandas.read_excel API 导入我的 Jupyter Notebook 时,日期字段的格式不正确:

excel = pd.read_excel('Libro.xlsx')

enter image description here

然后我得到了不同的 DATE 字段,因为我在 excel 文件中对其进行了格式化。我应该对 read_excel 应用什么参数才能显示我在 Excel 文件中设置的 DATE 列格式?

.info() 方法,将列输出为 int64

enter image description here

我已经尝试使用 pd.to_datetime 函数,但结果很奇怪:

enter image description here

在以下链接 sample_raw_data

中查找我用于我的项目的示例 Excel 文件

这里有一些代码可以用来重现从excel读入的DataFrame:

excel = pd.DataFrame({
    'CLaim': {0: 7538,1: 7538,2: 540,3: 540,4: 4605,5: 1740,6: 7605},'CODE1': {0: 359,1: 359,2: 428,3: 428,4: 1670,5: 134,6: 415},'AGE': {0: 71,1: 71,2: 73,3: 73,4: 40,5: 55,6: 56},'DATE': {0: 43797,1: 43797,2: 43754,3: 43754,4: 43803,5: 43823,6: 43818}
})

解决方法

要将此 Excel 日期转换为 datetime64[ns],请使用 to_datetime 以从 origin '1899-12-30' 偏移的天数获得单位:

excel = pd.read_excel('Libro.xlsx')
excel['DATE'] = pd.to_datetime(excel['DATE'],unit='d',origin='1899-12-30')

excel

   CLAIM  CODE1  AGE       DATE
0   7538    359   71 2019-11-28
1   7538    359   71 2019-11-28
2    540    428   73 2019-10-16
3    540    428   73 2019-10-16
4   4605   1670   40 2019-12-04
5   1740    134   55 2019-12-24
6   7605    415   56 2019-12-19

info

 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   CLAIM   7 non-null      int64         
 1   CODE1   7 non-null      int64         
 2   AGE     7 non-null      int64         
 3   DATE    7 non-null      datetime64[ns]

有关为什么这是基准日期的更多信息,请参阅 Why is 1899-12-30 the zero date in Access / SQL Server instead of 12/31?


converterDATE 也可以与 read_excel 一起使用:

excel = pd.read_excel(
    'Libro.xlsx',converters={
        'DATE': lambda x: pd.to_datetime(x,origin='1899-12-30')
    }
)

info

 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   CLAIM   7 non-null      int64         
 1   CODE1   7 non-null      int64         
 2   AGE     7 non-null      int64         
 3   DATE    7 non-null      datetime64[ns]

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...