yoshiserry
yoshiserry

Reputation: 21395

how to make a pandas dataframe column into a datetime object showing just the date to correctly sort

When I sort on month_date in dataframe (df) which contains

[2014-06-01, 2014-07-01, 2014-08-01,2014-09-01,2014-10-01] I get the following:

result = df.sort(['month_date'], ascending=True) 

However the result is (in this order):

10, 6, 7, 8, 9,

Whereas I expected 6, 7, 8, 9, 10

Maybe this is because I didn't specify that the month_date column should be a datetime object (and contain only the date and no time component.

How do I make the month_date column in my dataframe into a datetime object which only contains the date which pandas understands so it is sorted in the following order: 6, 7, 8, 9, 10,

UPDATE - YS-L correct answer below

df = pd.DataFrame({'month_date': ['2014-06-01', '2014-01-01', '2014-08-01','2014-09-01','2014-10-01']})
df['month_date'] = pd.to_datetime(df['month_date'])
print df.sort(['month_date'], ascending=True)

Upvotes: 1

Views: 3379

Answers (1)

YS-L
YS-L

Reputation: 14748

You can use pandas.to_datetime to convert the column into datetime type, and then perform sorting:

df = pd.DataFrame({'month_date': ['2014-06-01', '2014-01-01', '2014-08-01','2014-09-01','2014-10-01']})
df['month_date'] = pd.to_datetime(df['month_date'])
print df.sort(['month_date'], ascending=True)

Output:

           month_date
1 2014-01-01 00:00:00
0 2014-06-01 00:00:00
2 2014-08-01 00:00:00
3 2014-09-01 00:00:00
4 2014-10-01 00:00:00

Upvotes: 1

Related Questions