【发布时间】:2017-06-22 16:28:50
【问题描述】:
我通常从一些 csv 文件中调用数据并使用 pandas.to_datetime 函数将日期列更改为日期时间格式以进行进一步的数据处理。
但是,有时 to_datetime 函数运行良好,有时却不行。 它工作不稳定,我通常会花很多时间来调整数据时间格式..
我尝试了很多方法,但它们都不能稳定地工作。 有人可以帮我解决这个问题吗?
df1 = pd.read_csv("somefile.csv", encoding='utf-8', parse_dates=[0])
# the result turns out that the parse_dates does not work at all here
df1["Date"]= df1["Date"].apply(pd.to_datetime)
# after this change, the type(df1["Date"][0]) becomes pandas._libs.tslib.Timestamp
df1["Date"] = df1["Date"].dt.date.apply(lambda x: datetime.date(x.year,x.month,x.day))
# this code worked yesterday but not today anymore...
# TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'
这里的错误代码说“描述符'date'需要'datetime.datetime'对象但收到'int'” 我想将 df["Date"] 的类型更改为 datetime 类型而不是时间戳。
我的 pandas 数据框看起来像这样(仅显示日期列) 此处提供原始数据:https://www.dropbox.com/s/rrhy9my9yp1gy2y/test.csv?dl=0
Date
2015-01-07
2015-01-08
2015-01-09
2015-01-10
2015-01-11
我的python版本是2.7 被这个问题困扰了一段时间, 除了我之外,其他人的 to_datetime 功能都很好用吗?
【问题讨论】:
-
如果您可以发布原始数据并说明您认为它不起作用的原因会有所帮助
-
请查看错误消息 TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'。我只能将数据转换为时间戳而不是日期时间
-
我再次要求您提供重现您的问题的原始数据和代码,
read_csv的parse_datesarg 可以将多个列解析为datetime,pd.to_datetime也相当健壮。使用数据、代码、所需输出和错误编辑您的问题 -
谢谢,我把数据上传到Dropbox:dropbox.com/s/rrhy9my9yp1gy2y/test.csv?dl=0
-
df1["Date"] = df1["Date"].dt.date.apply(lambda x: datetime.date(x.year,x.month,x.day))的期望输出是什么?你需要日期 -df1["Date"] = df1["Date"].dt.date吗?还是元组df1["Date"].dt.date.apply(lambda x: (x.year,x.month,x.day))?