Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a pandas dataframe based on DateTime field

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
like image 465
user3447653 Avatar asked Jul 14 '16 14:07

user3447653


People also ask

How do you sort a DataFrame based on a date column?

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.

How do I sort by datetime in Python?

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.

How do you sort a DataFrame based on value?

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.


1 Answers

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)
like image 120
Jacob Avatar answered Oct 15 '22 19:10

Jacob