I am trying to sort a dataframe based on DateTime field which is of datatype datetime64[ns].
My dataframe looks like this:
Name DateTime1
P38 NaT
P62 2016-07-13 16:03:32.771
P59 2016-06-23 14:23:42.461
P07 NaT
P16 2016-06-23 14:02:06.237
P06 2016-07-13 16:03:52.570
P106 2016-07-13 19:56:22.676
When I sort it using DateTime field,
df.sort_values(by='DateTime1',ascending=True)
I do not get the desired result.
Output:
Name DateTime1
P16 2016-06-23 14:02:06.237
P59 2016-06-23 14:23:42.461
P62 2016-07-13 16:03:32.771
P06 2016-07-13 16:03:52.570
P106 2016-07-13 19:56:22.676
P38 NaT
P07 NaT
One thing to notice here is our DataFrame gets sorted in ascending order of dates, to sort the DataFrame in descending order we can pass an additional parameter inside the sort_values() function that will set ascending value to False and will return the DataFrame in descending order.
To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object.
You can sort by column values in pandas DataFrame using sort_values() method. To specify the order, you have to use ascending boolean property; False for descending and True for ascending. By default, it is set to True.
For others who might find this useful. I got it working by using the inplace argument like so:
df.sort_values(by='DateTime1', ascending=True, inplace=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With