python - how to make a pandas dataframe column into a datetime object showing just the date to correctly sort -
when sort on month_date in dataframe (df) contains
[2014-06-01, 2014-07-01, 2014-08-01,2014-09-01,2014-10-01] following:
result = df.sort(['month_date'], ascending=true)
however result (in order):
10, 6, 7, 8, 9,
whereas expected 6, 7, 8, 9, 10
maybe because didn't specify month_date column should datetime object (and contain date , no time component.
how make month_date column in dataframe datetime object contains date pandas understands sorted in 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)
you can use pandas.to_datetime
convert column datetime type, , 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
Comments
Post a Comment