【发布时间】:2019-07-21 08:50:53
【问题描述】:
所以我已经为此寻找解决方案,但似乎找不到适合我的解决方案。
我有一个 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
未排序的、尴尬的日期和时间格式。
我想按日期和时间排序(没有列标题,只有原始数据)
我使用了以下代码:
temp = [] # to hold dates
df = pd.read_csv(file, header=None, usecols=[1], engine='c')
for row in df.iterrows():
# grab date and time only
new = (repr(row[1]))[9:24]
temp.append(new)
temp.sort(key=lambda date: datetime.strptime(date, "%b %d %H:%M:%S"))
i = 0
while i < len(temp):
print(temp[i])
i += 1
这会以更整洁的排序格式输出日期和时间:
...
Oct 16 23:25:06
Oct 16 23:29:21
Oct 16 23:34:17
Oct 16 23:40:04
Oct 16 23:44:18
Oct 16 23:49:22
Oct 16 23:54:15
Oct 17 00:00:20
Oct 17 00:05:06
Oct 17 00:09:15
Oct 17 00:14:45
Oct 17 00:19:26
...
但我正在努力写回 CSV 并按该列对所有数据进行排序。
我想要的输出是编辑 CSV 以获得如下内容:
...
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
...
任何想法都将不胜感激,谢谢!
【问题讨论】:
-
您可以使用
usecols=[1,2]并为您的打印语句print("{} | {} | {}".format(i, temp[i], df[2][i]))...(while需要不缩进)。