paulchen
paulchen

Reputation: 1059

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?

Upvotes: 4

Views: 3803

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90899

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])

Upvotes: 3

Related Questions