Returns a new Series sorted by label if inplace argument is False, otherwise updates the original series and returns None.,The sort_index() function is used to sort Series by index labels.,Previous: Sort Pandas series in ascending or descending order by some criterion Next: Series-unstack() function,Returns: Series- The original Series sorted by the labels.
Syntax:
Series.sort_index(self, axis = 0, level = None, ascending = True, inplace = False, kind = 'quicksort', na_position = 'last', sort_remaining = True)
You can do this in number of different ways. For Series objects, you can simply pass your preferred order for the index like this:
>>> sr[['c', 'd', 'a', 'b']]
c 3
d 4
a 1
b 2
dtype: int64
Alternatively, both Series and DataFrame objects have a reindex
method. This allows you more flexibility when sorting the index. For instance, you can insert new values into the index (and even choose what value it should have):
>>> 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
Yet another option for both Series and DataFrame objects is the ever-useful loc
method of accessing index labels:
>>> sr.loc[['c', 'd', 'a', 'b']]
c 3
d 4
a 1
b 2
dtype: int64
Just use reindex
, for example:
In[3]: sr.reindex(['c', 'd', 'a', 'b'])
Out[3]:
c 3
d 4
a 1
b 2
dtype: int64
Returns a new Series sorted by label if inplace argument is False, otherwise updates the original series and returns None.,The original Series sorted by the labels or None if inplace=True.,If not None, apply the key function to the index values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect an Index and return an Index of the same shape.,Choice of sorting algorithm. See also numpy.sort() for more information. ‘mergesort’ and ‘stable’ are the only stable algorithms. For DataFrames, this option is only applied when sorting on a single column or label.
>>> s = pd.Series(['a', 'b', 'c', 'd'], index = [3, 2, 1, 4]) >>>
s.sort_index()
1 c
2 b
3 a
4 d
dtype: object
>>> s.sort_index(ascending = False) 4 d 3 a 2 b 1 c dtype: object
>>> s.sort_index(inplace = True) >>> s 1 c 2 b 3 a 4 d dtype: object
>>> s = pd.Series(['a', 'b', 'c', 'd'], index = [3, 2, 1, np.nan]) >>>
s.sort_index(na_position = 'first')
NaN d
1.0 c
2.0 b
3.0 a
dtype: object
>>> arrays = [np.array(['qux', 'qux', 'foo', 'foo',
...'baz', 'baz', 'bar', 'bar'
]),
...np.array(['two', 'one', 'two', 'one',
...'two', 'one', 'two', 'one'
])
] >>>
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8], index = arrays) >>>
s.sort_index(level = 1)
bar one 8
baz one 6
foo one 4
qux one 2
bar two 7
baz two 5
foo two 3
qux two 1
dtype: int64
>>> s.sort_index(level = 1, sort_remaining = False) qux one 2 foo one 4 baz one 6 bar one 8 qux two 1 foo two 3 baz two 5 bar two 7 dtype: int64
To sort a Pandas DataFrame by index, you can use DataFrame.sort_index() method.,To specify whether the method has to sort the DataFrame in ascending or descending order of index, you can set the named boolean argument ascending to True or False respectively.,In this example, we shall sort the DataFrame based on the descending order of index. For that, we shall pass ascending=False to the sort_index() method.,In this tutorial of Python Examples, we learned how to sort a Pandas DataFrame by index in ascending and descending orders.
Python Program
import pandas as pd
#create a dataframe
df_1 = pd.DataFrame(
[
['Arjun', 70, 86],
['Kiku', 80, 76],
['Mama', 99, 99],
['Lini', 79, 92]
],
index = [2, 1, 6, 5],
columns = ['name', 'aptitude', 'cooking'])
print(df_1)
#sort dataframe by index in ascending order
df_1 = df_1.sort_index(ascending = True)
print('\nDataFrame after sorting by index\n')
print(df_1)
Run the above program. We have printed the original DataFrame to the console, followed by sorted DataFrame.
name aptitude cooking 2 Arjun 70 86 1 Kiku 80 76 6 Mama 99 99 5 Lini 79 92 DataFrame after sorting by index name aptitude cooking 1 Kiku 80 76 2 Arjun 70 86 5 Lini 79 92 6 Mama 99 99
Run the program. The sorted dataframe has index [6 5 5 1]
in descending order.
name aptitude cooking 2 Arjun 70 86 1 Kiku 80 76 6 Mama 99 99 5 Lini 79 92 DataFrame after sorting by index name aptitude cooking 6 Mama 99 99 5 Lini 79 92 2 Arjun 70 86 1 Kiku 80 76