how to sort by english date format not american pandas .sort()

前端 未结 3 1444
情话喂你
情话喂你 2020-12-21 18:01
    symb                dates
4     BLK  01/03/2014 09:00:00
0     BBR  02/06/2014 09:00:00
21     HZ  02/06/2014 09:00:00
24   OMNI  02/07/2014 09:00:00
31   NOTE           


        
3条回答
  •  春和景丽
    2020-12-21 18:32

    I am not sure how you are getting the data, but if you are importing it from some source such as a CSV you could use pandas.read_csv and set parse_dates=True. The question is what is the type of the dates column? You an easily change them to datelike objects using `dateutil.parse.parse. For example,

    import pandas
    import dateutil
    data = {'symb': ['BLK', 'BBR', 'HZ', 'OMNI', 'NOTE', 'AMP', 'RBY'],
            'dates': ['01/03/2014 09:00:00', '02/06/2014 09:00:00', '02/06/2014 09:00:00',
                   '02/07/2014 09:00:00', '03/04/2014 09:00:00', '03/04/2016 09:00:00',
                   '04/07/2014 09:00:00']}
    df = pandas.DataFrame.from_dict(data)
    df.dates = df.dates.apply(dateutil.parser.parse)
    print df.to_string()
    
    # OUTPUT
    # 0 2014-01-03 09:00:00   BLK
    # 1 2014-02-06 09:00:00   BBR
    # 2 2014-02-06 09:00:00    HZ
    # 3 2014-02-07 09:00:00  OMNI
    # 4 2014-03-04 09:00:00  NOTE
    # 5 2016-03-04 09:00:00   AMP
    # 6 2014-04-07 09:00:00   RBY
    

    This gets you the [ISO8601 format] which may be preferable to the dd/mm/yyyy format, but if you must have that format you can use the code recommended by @umutto

提交回复
热议问题