Neta Geva
Neta Geva

Reputation: 31

how to sort by dates in format d-month-y in pandas?

I have a column with dates looking like this: 10-apr-18. when I'm transposing my df or doing anything with it, pandas automatically sort this column by the day (the first number) so it's not chronological.

I've tried to use to_datetime but because the month is a string it won't work.

How can I convert this to date OR cancel the automatically sorting (my raw data is already in the right order).

Upvotes: 1

Views: 2075

Answers (2)

jezrael
jezrael

Reputation: 862671

I suggest convert to datetimes with to_datetime and parameter format:

df = pd.DataFrame({'dates':['10-may-18','10-apr-18']})
#also working for me
#df['dates'] = pd.to_datetime(df['dates'])
df['dates'] = pd.to_datetime(df['dates'], format='%d-%b-%y')

df = df.sort_values('dates')
df['dates'] = df['dates'].dt.strftime('%d-%B-%y')
print (df)
         dates
1  10-April-18
0    10-May-18

df = pd.DataFrame({'dates':['10-may-18','10-apr-18']})
#also working for me
#df['dates'] = pd.to_datetime(df['dates'])
df['datetimes'] = pd.to_datetime(df['dates'], format='%d-%b-%y')

df = df.sort_values('datetimes')

df['full'] = df['datetimes'].dt.strftime('%d-%B-%y')
print (df)
       dates  datetimes         full
1  10-apr-18 2018-04-10  10-April-18
0  10-may-18 2018-05-10    10-May-18

Upvotes: 2

moys
moys

Reputation: 8033

df['dates'] = pd.to_datetime(df['dates'], format='%d-%b-%y').dt.strftime('%d/%B/%y')

Upvotes: 0

Related Questions