Search code examples
pythonpandassortingreindex

Rearranging Dataframe date


How do I rearrange dates after importing a csv file, such that the most recent date is at the bottom and the oldest date is at the top?

I have tried using reindex but it doesn't work.

hello Nukesor, the date for example will be..

 Date          Price
 5-2-2017    15.24
 4-2-2017    18.21
 3-2-2017    19.11
 2-2-2017    20.28
 1-2-2017    17.00

Now i will like to put 5-2-2017 at the bottom

Thanks guys.


Solution

  • You can use pd.to_datetime and then sort_values:

    df = df.assign(Date=pd.to_datetime(df['Date']))\
           .sort_values('Date')
    
    print(df)
    
            Date  Price
    4 2017-01-02  17.00
    3 2017-02-02  20.28
    2 2017-03-02  19.11
    1 2017-04-02  18.21
    0 2017-05-02  15.24