Pandas reindex Method implementation in Python with Examples

Pandas reindex Method implementation in Python with Examples

Pandas is the best python package for manipulating dataframe or series. There are many functions in it that help to manipulate the data. The pandas reindex is one of them. In this entire tutorial, you will know how to implement pandas reindex using various examples.

Examples of Pandas Reindex Implementation

In this section, you will know the various examples of pandas.Dataframe.reindex(). Please note that all the coding examples have been done on Jupyter Notebook. So I will suggest you do the coding parts on it for better understanding.

Let’s create a Sample dataframe for implementing reindex() method. Execute the below lines of code to create a sample dataframe.

import pandas as pd
data = {"col1":[10,20,30,40,50,60],
index =["A","B","C","D","E","F"]
df = pd.DataFrame(data,index=index)


Sample Dataframe for Pandas Reindex Method
Sample Dataframe for Reindex Method

Example 1:  Simple use of pandas reindex

In this example, I will first create a new index and then pass this index inside the pandas.DataFrame.reindex() method. Use the below lines of code.

new_index =["P","A","R","B","T","C"]


Simple use of Pandas Reindex
Simple use of Reindex

You can see in the output those indexes that do not have records in the dataframe, their columns have been filled by NaN. In the next example, you will know to reindex dataframe by filling the NaN value.

Example 2: Filling the NaN value with reindex

Fill the NaN with zero

To fill the value and reindex the dataframe you have to pass the fill_value argument inside the pandas.DataFrame.reindex(). Execute the below lines of code.

new_index =["P","A","R","B","T","C"]


Custom filling the NaN value
Custom filling the NaN value

Example 3: Apply reindex on columns

You can also reindex the columns. If you will do that then you will get NaN value in each record if that column is missing. For example, I want to reindex the columns with col1 and col3. Then if I will use the below lines of code then I will get the NaN value for the col3.



Applying pandas reindex on columns
Applying reindex on columns

These are the examples I have aggregated for the implementation of the reindex() method. I hope you have liked this tutorial. If you have any queries then you can contact us for help.


Pandas Documentation

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner