python - 在 Python 中以“Oct 03 10:06:20”格式按时间对 CSV 行进行排序
问题描述
所以我已经为此寻找解决方案,但似乎找不到适合我的解决方案。
我有一个格式为 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
...
任何想法将不胜感激,谢谢!
解决方案
不要将日期与其他数据分开。修改您的排序键,使其获取行的第二项,并将行传递给它。
那应该这样做:
result = sorted(df.iterrows(),key=lambda row: datetime.strptime(row[1], "%b %d %H:%M:%S"))
推荐阅读
- tableau-desktop - 通过电子邮件自动向客户发送 Tableau 工作表
- javascript - 如何在钩子函数中调用减速器动作
- python - 不允许字符串输入Python中的空格
- java - 我可以直接在 MVC 模式中传递一个值吗?
- storybook - 如何将数据传递给故事书中的子组件?
- python - python 带参数安装
- grails - How to use a multiple datasource with many laguage in grails 3.3
- java - What Does MapReactiveUserDetailsService Do in Spring Webflux Security Authentication?
- python-3.x - Using python asyncio with subprocesses
- python - 如何在pymeshlab中选择顶点数组?