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)
Parameter | Description |
---|---|
keys | A single column or list-like array. Must be the same length as DataFrame. |
drop | Do not insert an index into a DataFrame. |
append | If True , append columns to index. If False , do not append. By default, True . |
inplace | If True , the original DataFrame is updated. If False , a new object is updated and returned. |
verify_integrity | This 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 | ||
Greg | Jan | 165 |
Fred | Feb | 156 |
Helen | Mar | 196 |
Tim | Apr | 124 |
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.