Pandas Read_Excel 日期时间转换器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42958217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas Read_Excel Datetime Converter
提问by MattR
Using Python 3.6 and Pandas 0.19.2: How do you read in an excel file and change a column to datetime straight from read_excel
? Similar to This Question about converters and dtypes. But I want to read in a certain column as datetime
使用 Python 3.6 和 Pandas 0.19.2:您如何读取 excel 文件并将列直接从 更改为日期时间read_excel
?类似于关于转换器和 dtypes 的这个问题。但我想在某个专栏中阅读datetime
I want to change this:
我想改变这个:
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
into something like:
df1 = pd.read_excel(file, dtypes= {'COLUMN': datetime})
变成类似的东西:
df1 = pd.read_excel(file, dtypes= {'COLUMN': datetime})
The code does not error, but in my example, COLUMN
is still a dtype of int64
after calling print(df1['COLUMN'].dtype)
代码没有错误,但在我的例子中,COLUMN
仍然是int64
调用后的dtypeprint(df1['COLUMN'].dtype)
I have tried using np.datetime64
instead of datetime
. I have also tried using converters=
instead of dtypes=
but to no avail. This may be nit picky, but would be a nice feature to implement in my code.
我试过使用np.datetime64
代替datetime
. 我也试过使用 converters=
代替dtypes=
但无济于事。这可能有点挑剔,但在我的代码中实现将是一个很好的功能。
回答by EdChum
Typically reading excel sheets will use the dtypes defined in the excel sheets but you cannot specify the dtypes like in read_csv
for example. You can provide a converters
arg for which you can pass a dict of the column and func to call to convert the column:
通常,读取 excel 表将使用 excel 表中定义的 dtypes,但您不能指定 dtypes read_csv
,例如。您可以提供一个converters
arg,您可以为其传递列的 dict 和 func 以调用以转换列:
df1 = pd.read_excel(file, converters= {'COLUMN': pd.to_datetime})