pandas read_csv 中的日期时间数据类型 [英] datetime dtypes in pandas read_csv
问题描述
我正在读取具有多个日期时间列的 csv 文件.我需要在读取文件时设置数据类型,但日期时间似乎是一个问题.例如:
I'm reading in a csv file with multiple datetime columns. I'd need to set the data types upon reading in the file, but datetimes appear to be a problem. For instance:
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = ['datetime', 'datetime', 'str', 'float']
pd.read_csv(file, sep=' ', header=None, names=headers, dtype=dtypes)
运行时报错:
类型错误:无法理解数据类型datetime"
TypeError: data type "datetime" not understood
事后转换列,通过 pandas.to_datetime() 不是一个选项我不知道哪些列将是日期时间对象.该信息可以更改,并且来自通知我的 dtypes 列表的任何内容.
Converting columns after the fact, via pandas.to_datetime() isn't an option I can't know which columns will be datetime objects. That information can change and comes from whatever informs my dtypes list.
或者,我尝试使用 numpy.genfromtxt 加载 csv 文件,在该函数中设置 dtypes,然后转换为 pandas.dataframe,但它会使数据出现乱码.非常感谢任何帮助!
Alternatively, I've tried to load the csv file with numpy.genfromtxt, set the dtypes in that function, and then convert to a pandas.dataframe but it garbles the data. Any help is greatly appreciated!
推荐答案
为什么不起作用
没有为 read_csv 设置日期时间数据类型,因为 csv 文件只能包含字符串、整数和浮点数.
Why it does not work
There is no datetime dtype to be set for read_csv as csv files can only contain strings, integers and floats.
将 dtype 设置为 datetime 将使 Pandas 将日期时间解释为一个对象,这意味着您最终会得到一个字符串.
Setting a dtype to datetime will make pandas interpret the datetime as an object, meaning you will end up with a string.
pandas.read_csv()
函数有一个名为 parse_dates
使用它,您可以使用默认的 date_parser
(dateutil.parser.parser
) 将字符串、浮点数或整数即时转换为日期时间
Using this you can on the fly convert strings, floats or integers into datetimes using the default date_parser
(dateutil.parser.parser
)
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = {'col1': 'str', 'col2': 'str', 'col3': 'str', 'col4': 'float'}
parse_dates = ['col1', 'col2']
pd.read_csv(file, sep=' ', header=None, names=headers, dtype=dtypes, parse_dates=parse_dates)
这将导致 Pandas 将 col1
和 col2
作为字符串读取,它们很可能是(2016-05-05"等)并且在阅读了字符串,每一列的 date_parser 将作用于该字符串并返回该函数返回的任何内容.
This will cause pandas to read col1
and col2
as strings, which they most likely are ("2016-05-05" etc.) and after having read the string, the date_parser for each column will act upon that string and give back whatever that function returns.
pandas.read_csv()
函数也有一个关键字参数叫做date_parser
将此设置为 lambda 函数将使该特定函数用于解析日期.
Setting this to a lambda function will make that particular function be used for the parsing of the dates.
你必须给它函数,而不是函数的执行,因此这是正确的
You have to give it the function, not the execution of the function, thus this is Correct
date_parser = pd.datetools.to_datetime
这是错误的:
date_parser = pd.datetools.to_datetime()
熊猫 0.22 更新
pd.datetools.to_datetime
已重定位到 date_parser = pd.to_datetime
谢谢@stackoverYC
Thanks @stackoverYC
这篇关于 pandas read_csv 中的日期时间数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!