pandas Read_Excel日期时间转换器 [英] Pandas Read_Excel Datetime Converter

查看:331
本文介绍了 pandas Read_Excel日期时间转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python 3.6和Pandas 0.19.2:如何读取Excel文件并将列直接从 read_excel 更改为日期时间?类似于有关转换器和dtypes的问题。但是我想在特定列中读为 datetime

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

我想更改此内容:

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})

代码没有错误,但在我的示例中为<$ c在调用 print(df1 ['COLUMN']。dtype)<之后,$ c> COLUMN 仍然是 int64 的dtype。 / code>

The code does not error, but in my example, COLUMN is still a dtype of int64 after calling print(df1['COLUMN'].dtype)

我尝试使用 np.datetime64 而不是 datetime 。我也尝试使用 converters = 代替 dtypes = ,但无济于事。

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.

推荐答案

通常,阅读excel工作表会使用在excel工作表中定义的dtype,但是您不能像 read_csv 。您可以提供一个 转换器 arg,您可以为其传递列的字典和func来调用以转换列:

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:

df1 = pd.read_excel(file, converters= {'COLUMN': pd.to_datetime})

这篇关于 pandas Read_Excel日期时间转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆