How to reset index pandas dataframe after dropna() pandas dataframe?

Learn, how can we reset index pandas dataframe after dropna() pandas dataframe? By Pranit Sharma Last updated : October 01, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

While creating a DataFrame or importing a CSV file, there could be some NaN values in the cells. NaN values mean "Not a Number" which generally means that there are some missing values in the cell. To deal with this type of data, you can either remove the particular row (if the number of missing values is low) or you can handle these values.

Resetting index pandas dataframe after dropna() pandas dataframe

For this purpose, we will use the df.dropna() method by passing inplace=True to remove NaN value and then use the df.reset_index() method to reset the index with two parameters drop=True and inplace=True.

The syntax of the df.dropna() method is:

DataFrame.dropna(
    axis=0, 
    how=_NoDefault.no_default, 
    thresh=_NoDefault.no_default, 
    subset=None, 
    inplace=False
    )

Let us understand with the help of an example,

Python program to reset index pandas dataframe after dropna() pandas dataframe

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'Brand':['Samsung','LG','Whirlpool',np.nan],
    'Product':[np.nan,'AC','Washing Machine',np.nan]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display Original DataFrames
print("Created DataFrame:\n",df,"\n")

# Dropping nan values and resetting index
df.dropna(inplace=True)
df.reset_index(drop=True, inplace=True)

# Display result
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: Reset index pandas dataframe after dropna()

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.