-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?

2

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.