使用 Python 3.6 和 Pandas 0.19.2:如何读取 excel 文件并将列直接从 read_excel
更改为日期时间?类似于 This Question about converters and dtypes 。但我想在某个专栏中读作 datetime
我想改变这个:
import pandas as pd
import datetime
import numpy as np
file = 'PATH_HERE'
df1 = pd.read_excel(file)
df1['COLUMN'] = pd.to_datetime(df1['COLUMN']) # <--- Line to get rid of
变成类似: df1 = pd.read_excel(file, dtypes= {'COLUMN': datetime})
代码没有错误,但在我的示例中, COLUMN
仍然是 int64
的数据类型—调用 print(df1['COLUMN'].dtype)
我尝试使用 np.datetime64
而不是 datetime
。我也尝试过使用 converters=
而不是 dtypes=
但无济于事。这可能有点挑剔,但在我的代码中实现是一个不错的功能。
原文由 MattR 发布,翻译遵循 CC BY-SA 4.0 许可协议
通常阅读 excel 工作表将使用 excel 工作表中定义的数据类型,但您不能像
read_csv
中那样指定数据类型。您可以提供一个converters
arg,您可以为其传递列的字典和函数来调用以转换列: