【问题标题】:Python sorting CSV by date and timePython按日期和时间排序CSV
【发布时间】:2019-07-21 12:20:55
【问题描述】:

好的,我有一个格式为 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'

我认为我的问题是我正在正确访问该行,但我似乎无法自行访问日期值(该行的第二个元素),因此排序不起作用。

任何想法将不胜感激!谢谢

【问题讨论】:

    标签: python pandas csv sorting


    【解决方案1】:

    在对数据进行排序之前使用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
    

    【讨论】:

      【解决方案2】:

      您可以使用参数 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 : 布尔值,默认为 False

      如果 True 并且没有给出格式,尝试推断 日期时间字符串,如果可以推断,切换到更快的方法 解析它们。在某些情况下,这可以提高解析速度 ~5-10 倍。

      【讨论】:

        【解决方案3】:

        试试这个日期解析器:

        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])
        

        【讨论】:

          【解决方案4】:

          您可以在读取 csv 时使用parse_dates 转换为日期时间对象。

          例如:

          import pandas as pd
          
          df = pd.read_csv(filename, names=["Date", "Col"], sep="|", parse_dates=["Date"])
          df.sort_values(["Date"], inplace=True)
          print(df)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-01-17
            • 2012-09-09
            • 1970-01-01
            • 1970-01-01
            • 2018-04-14
            • 2012-08-16
            • 2021-09-23
            • 2016-08-09
            相关资源
            最近更新 更多