Sorting a pandas dataframe by its index
Question:
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?
Answers:
I think you need sort_index
:
all_data = all_data.sort_index()
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?
I think you need sort_index
:
all_data = all_data.sort_index()