Pandas DataFrame – Remove index

Pandas DataFrame – Remove index

To remove the index of a DataFrame in Pandas, call reset_index() method on the given DataFrame and specify the argument drop=False.

The reset_index() method drops the present index, and sets the default integer index for the DataFrame.

In this tutorial, we will go through an example, with step by step explanation of how to remove index from a DataFrame using reset_index() method.

Example

1. Remove index of DataFrame using reset_index() method in Pandas

In this example, we are given a DataFrame in df_input with a custom index. We have to remove the index of this DataFrame using reset_index() method.

Steps

  1. Given a DataFrame in df_input with specific index.
df_input = pd.DataFrame({
    'A': [2, 4, 6],
    'B': [1, 3, 5]},
    index = ['X', 'Y', 'Z'])
  1. Call reset_index() method on the DataFrame df_input and pass the argument drop=True.
df_input.reset_index(drop=True)
  1. By default, the reset_index() method returns a new DataFrame created from the given DataFrame by removing the existing index, and reseting to default integer index. You may assign the returned DataFrame to a variable df_result.
df_result = df_input.drop(columns=['B'])
  1. You may print the DataFrame df_result to output.
print(df_result)

Program

The complete program to remove the index of a given DataFrame.

Python Program

import pandas as pd

# Take a DataFrame
df_input = pd.DataFrame({
    'A': [2, 4, 6],
    'B': [1, 3, 5]},
    index = ['X', 'Y', 'Z'])

# Remove index
df_result = df_input.reset_index(drop=True)
print(df_result)
Run Code Copy

Output

   A  B
0  2  1
1  4  3
2  6  5

Summary

In this Pandas Tutorial, we learned how to remove the index from DataFrame using DataFrame reset_index() method, with examples.

Related Tutorials

Code copied to clipboard successfully 👍