Pandas DataFrame set_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 set_index()

The set_index() method sets the DataFrame index using existing columns/rows.

The syntax for this method is as follows:

DataFrame.set_index(keys, drop=True, append=False, 
                    inplace=False, verify_integrity=False)
ParameterDescription
keysA single column or list-like array. Must be the same length as DataFrame.
dropDo not insert an index into a DataFrame.
appendIf True, append columns to index. If False, do not append. By default, True.
inplaceIf True, the original DataFrame is updated. If False, a new object is updated and returned.
verify_integrityThis parameter checks the new index for duplicates (columns). Set to False for faster performance.

For this example, the Salesperson(s) who sold the highest number of cars over four (4) months display.

df = pd.DataFrame({'Salesman':    ['Greg', 'Fred', 'Helen', 'Tim'],
                   'Month':         ['Jan', 'Feb', 'Mar', 'Apr'],
                   'Sold':             [165, 156, 196, 124]})

result = df.set_index('Salesperson')
print(result)
  • Line [1] creates a Dictionary of Lists and saves it to df.
  • Line [2] sets the index to ‘Salesperson’ and saves it to the result variable.
  • Line [3] outputs the result to the terminal.

Output

 Month Sold
Salesperson
GregJan165
FredFeb156
HelenMar196
TimApr124

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.