好的,所以我有一个格式的CSV文件:
1 | Thu Oct 04 21:47:53 GMT+01:00 2018 | 35.3254
2 | Sun Oct 07 09:32:11 GMT+01:00 2018 | 45.7824
3 | Mon Oct 01 01:00:44 GMT+01:00 2018 | 94.1246
...
3023 | Sat Oct 23 01:00:44 GMT+01:00 2018 | 67.2007
我想按日期和时间排序,所以我得到类似的东西:
...
456 | Oct 16 23:25:06 | 45.6547
457 | Oct 16 23:29:21 | 64.3453
458 | Oct 16 23:34:17 | 27.6841
459 | Oct 16 23:40:04 | 78.6547
460 | Oct 16 23:44:18 | 11.6547
461 | Oct 16 23:49:22 | 34.6547
462 | Oct 16 23:54:15 | 37.6547
463 | Oct 17 00:00:20 | 68.6547
464 | Oct 17 00:05:06 | 07.6547
465 | Oct 17 00:09:15 | 13.6547
466 | Oct 17 00:14:45 | 37.6547
467 | Oct 17 00:19:26 | 84.6547
...
日期和时间是一个讨厌的格式,所以我尝试了以下内容:
df = pd.read_csv(file, header=None, engine='c', delimiter=',' )
for index, row in df.iterrows():
result = sorted(df.iterrows(),key=lambda row: datetime.strptime((str(row[1]))[9:24], "%b %d %H:%M:%S"))
print (result)
([9:24]应该允许我拼接字符串以获得Oct 16 23:29:21
例如)
我收到错误:
ValueError: time data 'ame: 0, dtype: ' does not match format '%b %d %H:%M:%S'
我认为我的问题是我正在正确访问行,但我似乎无法访问它自己的日期值(行的第二个元素),因此排序不起作用。
任何想法将不胜感激!谢谢
您可以使用参数infer_datetime_format。以下示例数据示例:
>> df['date'] = pd.to_datetime(df.date, infer_datetime_format = True)
>> df.sort_values(by = 'date', ascending = True, inplace = True)
>> df.date
2 2018-10-01 02:00:44
0 2018-10-04 22:47:53
1 2018-10-07 10:32:11
3 2018-10-23 02:00:44
Name: date, dtype: datetime64[ns]
来自pandas.to_datetime()文档:
infer_datetime_format:boolean,默认为False
如果为True且未给出格式,请尝试推断日期时间字符串的格式,如果可以推断,请切换到更快的解析方法。在某些情况下,这可以将解析速度提高约5-10倍。
您可以在读取csv时使用parse_dates
转换为datetime对象。
例如:
import pandas as pd
df = pd.read_csv(filename, names=["Date", "Col"], sep="|", parse_dates=["Date"])
df.sort_values(["Date"], inplace=True)
print(df)
试试这个日期解析器:
from dateutil.parser import parse
print(parse(timestr=('Thu Oct 04 21:47:53 GMT+01:00 2018'), dayfirst=False,fuzzy_with_tokens=True)[0])
在排序数据之前使用strftime
import pandas as pd
df = pd.DataFrame({'Date': ['Thu Oct 04 21:47:53 GMT+01:00 2018','Sun Oct 07 09:32:11 GMT+01:00 2018']})
df['Clean_Date'] = df.Date.apply(lambda x: pd.to_datetime(x).strftime('%b %d %H:%M:%S'))
print(df)
Date Clean_Date
0 Thu Oct 04 21:47:53 GMT+01:00 2018 Oct 04 21:47:53
1 Sun Oct 07 09:32:11 GMT+01:00 2018 Oct 07 09:32:11