33

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?

2 Answers 2

79

I think you need sort_index:

all_data = all_data.sort_index()
Sign up to request clarification or add additional context in comments.

Comments

1

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]

res

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.