How to sort a series or DataFrame using a given index?

Suppose I have a series like this:

In [19]: sr
Out[19]: 
a    1
b    2
c    3
d    4
dtype: int64

In [20]: sr.index
Out[20]: Index([u'a', u'b', u'c', u'd'], dtype='object')

Instead of sorting the lexicographically, I would like to sort the series based on a custom order, say cdab. How can i do this?

What if it is a DataFrame; How can I sort it by the specified index list?

+4
source share
2 answers

You can do this in several ways. For series objects, you can simply pass in your preferred index order as follows:

>>> sr[['c','d','a','b']]
c    3
d    4
a    1
b    2
dtype: int64

Series DataFrame reindex. . , ( , ):

>>> sr.reindex(['c','d','a','b','e'])
c     3
d     4
a     1
b     2
e   NaN      # <-- new index location 'e' is filled with NaN
dtype: int64

Series DataFrame - loc :

>>> sr.loc[['c','d','a','b']]
c    3
d    4
a    1
b    2
dtype: int64
+7

reindex, :

In [3]: sr.reindex(['c', 'd', 'a', 'b'])
Out[3]: 
c    3
d    4
a    1
b    2
dtype: int64
+2

All Articles