Home > Software design >  How to sort numpy.recarray based on datetime field
How to sort numpy.recarray based on datetime field

Time:05-09

I have built a recarray with np.rec.fromarrays and following structure :

dtype=np.dtype([('layers', 'U256'), ('hours', datetime.datetime), ('points', 'U256')]))

I get an object like this :

[('image1.jpg', datetime.datetime(1900, 1, 1, 21, 20), 'mypoints.points')
 ('image2.jpg', datetime.datetime(1900, 1, 1, 21, 15), 'mypoints.points')]

with recarray type. I want to sort my recarray based on the second column containing datetime. I tried numpy.recarray.sort but it returns a NoneType object. I use it like this :

mytable.sort(order='hours')

I also tried to pass kind='quicksort' to the function but doesn't understand its usefulness.

CodePudding user response:

I tried to reproduce your data

x1=np.array(['image1.jpg', 'image2.jpg'])
x2=np.array([datetime.datetime(1900, 1, 1, 21, 10), datetime.datetime(1900, 1, 1, 21, 9)])
x3=np.array(['mypoints.points', 'mypoints.points'])
    
array = np.rec.fromarrays([x1, x2, x3], dtype=np.dtype([('layers', 'U256'), ('hours', datetime.datetime), ('points', 'U256')]))

Output:

rec.array([('image1.jpg', datetime.datetime(1900, 1, 1, 21, 20), 'mypoints.points'),
           ('image2.jpg', datetime.datetime(1900, 1, 1, 21, 15), 'mypoints.points')],
          dtype=[('layers', '<U256'), ('hours', 'O'), ('points', '<U256')])

But was not able to get same error... array.sort(order='hours') works fine

rec.array([('image2.jpg', datetime.datetime(1900, 1, 1, 21, 15), 'mypoints.points'),
           ('image1.jpg', datetime.datetime(1900, 1, 1, 21, 20), 'mypoints.points')],
          dtype=[('layers', '<U256'), ('hours', 'O'), ('points', '<U256')])
  • Related