Pandas DataFrame sort_index() Method


Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import numpy as np 

DataFrame sort_index()

The sort_index() method sorts the DataFrame.

The syntax for this method is as follows:

DataFrame.sort_index(axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, ignore_index=False, key=None)
ParameterDescription
axisIf zero (0) or index is selected, apply to each column. Default is 0 (column). If zero (1) or columns, apply to each row.
levelThis parameter is an integer, level name, or a list of integers/level name(s). If not empty, a sort is performed on values in the selected index level(s).
ascendingBy default, True. Sort is conducted in ascending order. If False, descending order.
inplaceIf False, create a copy of the object. If True, the original object updates. By default, False.
kindAvailable options are quicksort, mergesort, heapsort, or stable. By default, quicksort. See numpy.sort for additional details.
na_positionAvailable options are first and last (default). If the option is first, all NaN values move to the beginning, last to the end.
ignore_indexIf True, the axis numbering is 0, 1, 2, etc. By default, False.
keyThis parameter applies the function to the values before a sort. The data must be in a Series format and applies to each column.

For this example, a comma-delimited CSV file is read into a DataFrame. This DataFrame sorts on the index Country column.

df = pd.read_csv('countries.csv')
df = df.set_index('Country')
result = df.sort_index()
print(result)
  • Line [1] reads in a comma-delimited CSV file and saves to df.
  • Line [2] sets the index of the DataFrame to Country. The output saves to df (over-writing original df).
  • Line [3] sorts the DataFrame (df) on the indexed column (Country) in ascending order (default). The output saves to result.
  • Line [4] outputs the result to the terminal.

Output

 CountryPopulationArea
ChinaBeijing 1400050000  9596961
FranceParis   67081000   551695
GermanyBerlin   83783942   357021
IndiaDheli 1352642280  3287263
ItalyRome   60317116   301338
PolandWarsaw   38383000   312685
RussiaMoscow  146748590 17098246
SpainMadrid   47431256   498511
USAWashington  328239523  9833520

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.