Wednesday, December 25, 2024
Google search engine
HomeLanguagesHow to Drop the Index Column in Pandas?

How to Drop the Index Column in Pandas?

In this article, we will discuss how to drop the index column in pandas using Python.

First we have to create the dataframe with student details and set the index by using set_index() function

Syntax:

dataframe.set_index([pandas.Index([index_values…….])])

where

  • dataframe is the input dataframe
  • Index_values are the values to be given as indexes to the dataframe

Example: Setting index column for the dataset. The initial plot does that the changes are apparent.

Python3




# import pandas module
import pandas as pd
  
# create dataframe with 3 columns
data = pd.DataFrame({
    "id": [7058, 7059, 7072, 7054],
    "name": ['sravan', 'jyothika', 'harsha', 'ramya'],
    "subjects": ['java', 'python', 'html/php', 'php/js']
}
)
  
# set the index values
data = data.set_index(
    [pd.Index(['student-1', 'student-2', 'student-3', 'student-4'])])
  
# display dataframe
print(data)


Output:

Now we can drop the index columns by using reset_index() method. It will remove the index values and set the default values from 0 to n values

Syntax:

dataframe.reset_index(drop=True, inplace=True)

where

  • dataframe is the input dataframe
  • drop is set to True to remove index values
  • inplace is to set the default integers

Example: Drop the index columns

Python3




# import pandas module
import pandas as pd
  
# create dataframe with 3 columns
data = pd.DataFrame({
    "id": [7058, 7059, 7072, 7054],
    "name": ['sravan', 'jyothika', 'harsha', 'ramya'],
    "subjects": ['java', 'python', 'html/php', 'php/js']
}
)
  
# set the index values
data = data.set_index(
    [pd.Index(['student-1', 'student-2', 'student-3', 'student-4'])])
  
# display dataframe
print(data)
  
  
# drop the index columns
data.reset_index(drop=True, inplace=True)
  
# display
print(data)


Output:

RELATED ARTICLES

Most Popular

Recent Comments