Reputation: 8521
The following is a sample of my dataframe. As you'll notice, the index (which is datetimeindex) is not sorted.
Item Details Unit Op. Qty Price Op. Amt.
Month
2013-04-01 5 In 1 Pcs -56.0 172.78 -9675.58
2014-01-01 14" Blad Pcs -5.0 157.49 -787.45
2013-09-01 Zorrik 311 Gram Pcs -1.0 270.01 -270.01
I wanted to sort the index and its respective rows also. I found the following way to sort the datetimeindex:
all_data.index.sort_values()
DatetimeIndex(['2013-04-01', '2013-04-01', '2013-04-01', '2013-04-01',
'2013-04-01', '2013-04-01', '2013-04-01', '2013-04-01',
'2013-04-01', '2013-04-01',
...
'2014-02-01', '2014-02-01', '2014-02-01', '2014-02-01',
'2014-02-01', '2014-02-01', '2014-02-01', '2014-02-01',
'2014-02-01', '2014-02-01'],
dtype='datetime64[ns]', name=u'Month', length=71232, freq=None)
But it is sorting only the index; how can I sort the entire dataframe according to the sorted index?
Upvotes: 33
Views: 65679
Reputation: 23141
df.sort_index()
does the job but if the index is already sorted separately (as in the OP) and you want to sort the dataframe by it, then loc
is what you want.
sorted_idx = df.index.sort_values()
df = df.loc[sorted_idx]
Upvotes: 2