Reindex Objects

In this lesson, reindexing methods for pandas objects is explained.

Re-indexing #

This method allows for adding new indexes and columns in Series and DataFrames without disturbing the initial setting of the objects. The following illustration might make it clear.

The value of the index C in the last slide of the illustration is automatically set to NaN because no value was defined to it.

Note: Re-indexing rules are the same for both Series and DataFrame objects.

The function used for this purpose is reindex(). It is called by a Series or a DataFrame object, and a list of indexes is passed as a parameter.

Re-indexing in Series

Let’s take the same example from the ...

Press + to interact
#importing pandas in our program
import pandas as pd
# Defining a series object
srs1 = pd.Series([11.9, 36.0, 16.6, 21.8, 34.2], index = ['China', 'India', 'USA', 'Brazil', 'Pakistan'])
# Set Series name
srs1.name = "Growth Rate"
# Set index name
srs1.index.name = "Country"
srs2 = srs1.reindex(['China', 'India', 'Malaysia', 'USA', 'Brazil', 'Pakistan', 'England'])
print("The series with new indexes is:\n",srs2)
srs3 = srs1.reindex(['China', 'India', 'Malaysia', 'USA', 'Brazil', 'Pakistan', 'England'], fill_value=0)
print("\nThe series with new indexes is:\n",srs3)
...