微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – Pandas read_csv无法将ISO8601识别为datetime dtype

目前我使用pandas将csv文件读入DataFrame,使用第一列作为索引.第一列是ISO 8601格式,因此根据read_csv的文档,它应该被识别为日期时间:

In [1]: import pandas as pd

In [2]: df = pd.read_csv('data.csv', index_col=0)

In [3]: print df.head()
                        U     V     Z    Ubar    Udir
2014-11-01 00:00:00  0.73 -0.81  0.46  1.0904  317.97
2014-11-01 01:00:00  1.26 -1.50  0.32  1.9590  319.97
2014-11-01 02:00:00  1.50 -1.80  0.13  2.3431  320.19
2014-11-01 03:00:00  1.39 -1.65  0.03  2.1575  319.89
2014-11-01 04:00:00  0.94 -1.08 -0.03  1.4318  318.96

但是,在查询索引dtype时,它返回’object’:

In [4]: print df.index.dtype
object

然后我必须手动将其转换为datetime dtype:

In [5]: df.index = pd.to_datetime(df.index)

In [6]: print df.index.dtype
datetime64[ns]

有没有办法在调用read_csv()时自动将索引设置为datetime dtype?

解决方法:

read_csv文档描述了parse_dates参数:

parse_dates : boolean or list of ints or names or list of lists or dict, default False
– boolean. If True -> try parsing the index.
– list of ints or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.
– list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as
a single date column.
– dict, e.g. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’
Note: A fast-path exists for iso8601-formatted dates.

由于您要解析索引,您可以使用:

 import pandas as pd
 df = pd.read_csv('data.csv', index_col=0, parse_dates=True)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐