-1

I want to sort my numpy array using certain column. The shape looks like:

array([['0', 'item_805696', '2021-02-11 13:03:42'],
       ['0', 'item_386903', '2021-02-11 13:03:52'],
       ['0', 'item_3832', '2021-02-11 13:04:07'],
       ['0', 'item_849824', '2021-02-11 13:05:04'],
       ['0', 'item_815594', '2021-02-11 13:06:19']], dtype='<U21')

I wanna convert 3rd column of my array into datetime format and sort it by it.
How can I do this in quick easy way?

JS J
  • 33
  • 4
  • sort with this https://stackoverflow.com/questions/5166842/sort-dates-in-python-array and then use this https://stackoverflow.com/questions/2828059/sorting-arrays-in-numpy-by-column – Mark Kapilyan Feb 07 '23 at 17:06
  • 2
    Which part are you having trouble with? This isn't a discussion forum or tutorial. Please take the [tour] and take the time to read [ask], [mre] and the other links found on those pages. – wwii Feb 07 '23 at 17:09

1 Answers1

1

Combine conversion to datetime64 and argsort:

a = np.array([['0', 'item_805696', '2021-02-11 13:03:42'],
              ['0', 'item_386903', '2021-02-11 13:03:52'],
              ['0', 'item_3832', '2021-02-11 13:04:07'],
              ['0', 'item_849824', '2021-02-11 13:05:04'],
              ['0', 'item_815594', '2021-02-11 13:06:19']], dtype='<U21')

out = a[np.argsort(a[:, 2].astype('datetime64'))]

Note that given your lexicographically sortable string, you can also skip the conversion to datetime64. Output:

array([['0', 'item_805696', '2021-02-11 13:03:42'],
       ['0', 'item_386903', '2021-02-11 13:03:52'],
       ['0', 'item_3832', '2021-02-11 13:04:07'],
       ['0', 'item_849824', '2021-02-11 13:05:04'],
       ['0', 'item_815594', '2021-02-11 13:06:19']], dtype='<U21')
mozway
  • 194,879
  • 13
  • 39
  • 75