I have the following column in a csv file. How can I arrange the entire dataframe from oldest to newest. I currently have the following code: po_dataset.sort_values("date",ascending=True) But I am not getting the proper order.
Date
12/12/2020
14/11/2020
28/11/2020
CodePudding user response:
First convert the values in the date
column to datetime
objects, like this:
po_dataset["date"] = pd.to_datetime(po_dataset["date"], format="%d/%m/%Y")
You can see a complete list of the various %
-formats here.
Then sort them:
po_dataset.sort_values("date", ascending=True)
CodePudding user response:
Convert the date (strings) to datetime type:
df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
then you can sort values. If you don't want to change your data type (which is not recommended), then convert the dates to a temporary series, and reindex:
df.loc[pd.to_datetime(df['Date'], dayfirst=True).sort_values().index]
Output:
Date
1 14/11/2020
2 28/11/2020
0 12/12/2020