Learn about Reset Index Pandas
Introduction
In this article, we will learn about reset index pandas on pandas DataFrame with several examples. We have previously learned that Pandas is a Python library used for working with data sets. It offers tools for data exploration, cleaning, analysis, and manipulation.
To reset the index on the pandas DataFrame, use the DataFrame.reset index() method. This returns a DataFrame and accepts the arguments level, drop, inplace, col level, and col fill. Use of inplace=True causes it to return Nothing. To set a column as the index, use pandas.DataFrame.set index().
Below are some quick examples of reset index on DataFrame.
# Quick examples of reset index |
pandas.DataFrame.reset_index() Syntax
Following is the syntax of the pandas.DataFrame.reset_index().
DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')
- level – Takes int, str, tuple, or list, default None
- drop – bool, default False. When set to True, it ignores setting the old index as a column.
- inplace – bool, default False. When set to True, it updates the existing DataFrame object.
- col_level – If the columns have multiple levels, determine which level the labels are inserted into.
- col_fill – If the columns have multiple levels, determine how the other levels are named.
Let’s create a pandas DataFrame with examples
import pandas as pd |
Yields below output
Courses Fee Duration |
pandas Reset Index on DataFrame Example
Now let's reset the DataFrame index using the pandas.DataFrame.reset index() syntax. The old index is added to the DataFrame as a column when the index is reset, and a new sequential index is used instead.
# reset index on DataFrame |
Yields below output.
index Courses Fee Duration |
If you don’t want to add the existing index as a column, use drop=True param and also use inplace=True to update the existing DataFrame.
# drop index as column |
Yields below output
Courses Fee Duration |
Reset index name on DataFrame
Let's now examine how to rename an index in a pandas DataFrame. DataFrame is created by default with the index name set to "index."
# Set index name |
Yields below output.
Courses Fee Duration |
Complete Example of Reset Index on DataFrame
import pandas as pd |
Conclusion
In this article, you have learned how to reset the index on DataFrame by using different prams on the reset_index() method.