Reputation: 733
I have this dataframe whose head looks like this:
Out[8]:
Date Value
0 2016-06-30 481100.0
1 2016-05-31 493800.0
2 2015-12-31 514000.0
3 2015-10-31 510700.0
I want to use the Dates column as the index and then sort the rows based on order of the Dates.
When I try to sort it based on the first column with:
df.set_index('Date', inplace=True)
the head then looks like this:
Value
Date
2016-06-30 481100.0
2016-05-31 493800.0
2015-12-31 514000.0
2015-10-31 510700.0
Not only the dataframe is not ordered based on the dates, the headers are messed up:
Why does this happen and how should I correct it?
Upvotes: 0
Views: 293
Reputation: 21574
You should use sort_values
:
In [3]: df
Out[3]:
Date Value
0 2016-06-30 481100.0
1 2016-05-31 493800.0
2 2015-12-31 514000.0
3 2015-10-31 510700.0
In [4]: df = df.sort_values(by='Date')
In [5]: df
Out[5]:
Date Value
3 2015-10-31 510700.0
2 2015-12-31 514000.0
1 2016-05-31 493800.0
0 2016-06-30 481100.0
EDIT: Once sorted, you can set your desired column as index of the dataframe:
In [6]: df.set_index('Date', inplace=True)
In [7]: df
Out[7]:
Value
Date
2015-10-31 510700.0
2015-12-31 514000.0
2016-05-31 493800.0
2016-06-30 481100.0
Upvotes: 2