Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort numpy array by datetime objects

I have two numpy arrays: date_month of the form

array([datetime.datetime(2013, 1, 1, 12, 0),
       datetime.datetime(2013, 9, 1, 12, 0),
       datetime.datetime(2013, 5, 1, 12, 0)], dtype=object)

and emission_each_month of the form

array([5,7,3])

The entry 5 of emission_each_month belongs to the timestamp (2013, 1, 1, 12, 0), 7 belongs to (2013, 9, 1, 12, 0), 3 belongs to (2013, 5, 1, 12, 0). (In reality my data is much bigger)

I would like to have my data sorted by date. How do I that?

like image 845
paulchen Avatar asked Sep 16 '25 01:09

paulchen


1 Answers

You can use numpy.argsort() to get the indexes of the sorted array of datetime object , and then use the returned indices to sort the array - emission_each_month . Example -

In [66]: import datetime

In [67]: import numpy as np

In [68]: n = np.array([5,7,3])

In [69]: d = np.array([datetime.datetime(2013, 1, 1, 12, 0), datetime.datetime(2013, 9, 1, 12, 0), datetime.datetime(2013, 5, 1, 12, 0)])

In [72]: n[np.argsort(d)]
Out[72]: array([5, 3, 7])
like image 67
Anand S Kumar Avatar answered Sep 17 '25 15:09

Anand S Kumar