Pandas reindex Method implementation in Python with Examples

Pandas reindex Method implementation in Python with Examples

GET FREE AMZAON AUDIOBOOKS

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],
"col2":[100,200,300,400,500,600]}
index =["A","B","C","D","E","F"]
df = pd.DataFrame(data,index=index)
print(df)

Output

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"]
print(df.reindex(new_index))

Output

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"]
print(df.reindex(new_index,fill_value="miss"))

Output

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.

print(df.reindex(columns=["col1","col3"]))

Output

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.

Source:

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.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner