Home > other >  Sorting np.array of dates
Sorting np.array of dates

Time:12-01

I'm having this matrix of dates that I would like to sort by dates and then have back in the same format as it started

data = np.array(
    [[2015, 1, 1, 23, 4, 59],
     [2015, 4, 30, 23, 5, 1],
     [2015, 1, 1, 23, 5, 25],
     [2015, 2, 15, 58,5, 0],
     [2015, 5, 20, 50, 27, 37],
     [2015, 6, 21, 25, 27, 29]])

I tried datetime.datetime, but couldn't convert the data back to this format

CodePudding user response:

You can sort your data without the conversion to datetime, since the date/time components already appear in sorted order (year, month, etc.). So a np.sort(data, axis=0) should do:

import numpy as np

data = np.array(
    [[2015, 1, 1, 23, 4, 59],
      [2015, 4, 30, 23, 5, 1],
      [2015, 1, 1, 23, 5, 25],
      [2015, 2, 15, 58,5, 0],
      [2015, 5, 20, 50, 27, 37],
      [2015, 6, 21, 25, 27, 29]])

np.sort(data, axis=0)
array([[2015,    1,    1,   23,    4,    0],
        [2015,    1,    1,   23,    5,    1],
        [2015,    2,   15,   23,    5,   25],
        [2015,    4,   20,   25,    5,   29],
        [2015,    5,   21,   50,   27,   37],
        [2015,    6,   30,   58,   27,   59]])
  • Related