0

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.

jpp
  • 159,742
  • 34
  • 281
  • 339
Jonathan
  • 424
  • 4
  • 14
  • How exactly does the date in your dataframe look like? What type are your entries in the date row? You might just need to call `df['Date'] =pd.to_datetime(df.Date)` and then sort by this column. – Nukesor Sep 09 '18 at 11:52
  • Hi Nukesor i have re-edited the question. Please take a look and kindly give your feedback. Thanks – Jonathan Sep 09 '18 at 12:58

2 Answers2

1

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
jpp
  • 159,742
  • 34
  • 281
  • 339
1

Try this:

df['Date'] = pd.to_datetime(df['Date'])
df.sort_values('Date', ascending = True, inplace=True)

First line converts date to comprehensible datetime format for the dataframe. Second line sorts the values in ascending order. Without first line order would be as a string, and that is not the behaviour expected.