The Wayback Machine - https://web.archive.org/web/20240906061920/https://www.geeksforgeeks.org/python-pandas-dataframe-set_index/
Open In App

Python | Pandas DataFrame.set_index()

Last Updated : 03 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will discuss Pandas DataFrame.set_index() in Python. Python stands out as an excellent language for data analysis, largely due to its outstanding ecosystem of data-centric packages. Among these packages, Pandas plays a significant role in simplifying importing and analyzing data.

Pandas DataFrame.set_index() Syntax

Syntax:  DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)

Parameters: 

  • keys: Column name or a list of column names.
  • drop: A Boolean value that, if True, drops the column used for the index.
  • append: If True, appends the specified column to the existing index column.
  • inplace: If True, the changes are made in the DataFrame itself.
  • verify_integrity: If True, checks the new index column for duplicates. 

What is Pandas DataFrame.set_index() ?

The Pandas Dataframe.set_index() method is used to assign a list, series, or another data frame as the index of a given data frame. It is particularly useful when combining multiple data frames, allowing for easy modification of the index. While an index column can be specified during data frame creation, set_index() provides a flexible way to change the index later on. In essence, it allows you to set a List, Series, or Data frame as the index of a Data Frame. But sometimes a data frame is made out of two or more data frames and hence later index can be changed using this method.

To download the CSV file used, Click Here.

Pandas DataFrame.set_index() Examples

Below are proper illustrations of the examples for Pandas DataFrame.set_index().

  • Pandas Set Index to Column
  • Multiple index Column 
  • Setting a single Float column as Index
  • Setting three columns as MultiIndex
  • Pandas Set Index of Specific Column

Pandas Set Index to Column

In this example, we are Changing Index column, First Name column has been made the index column of Data Frame. 

Python3




# importing pandas package
import pandas as pd
 
# making data frame from csv file
data = pd.read_csv("employees.csv")
 
# setting first name as index column
data.set_index("First Name", inplace = True)
 
# display
data.head()


Output: Before operation –

After operation – 

As shown in the output images, earlier the index column was a series of number but later it has been replaced with First name.

Pandas Set Index to Multiple index Column 

In this example, two columns will be made as index column. Drop parameter is used to Drop the column and append parameter is used to append passed columns to the already existing index column. 

Python3




# importing pandas package
import pandas as pd
 
# making data frame from csv file
data = pd.read_csv("employees.csv")
 
# setting first name as index column
data.set_index(["First Name", "Gender"], inplace = True,
                            append = True, drop = False)
 
# display
data.head()


Output: 

As shown in the output Image, the data is having 3 index columns.  

Pandas Dataframe Index Setting a single Float column as Index

In this example the below code snippet uses the Pandas library to create a DataFrame named ‘df’ from a nested list of student data. It sets the ‘Agg_Marks’ column as the index and displays the resulting DataFrame with columns ‘Name’, ‘Age’, ‘City’, and ‘Country’.

Python3




# importing pandas library
import pandas as pd
 
# creating and initializing a nested list
students = [['jack', 34, 'Sydeny', 'Australia',85.96],
            ['Riti', 30, 'Delhi', 'India',95.20],
            ['Vansh', 31, 'Delhi', 'India',85.25],
            ['Nanyu', 32, 'Tokyo', 'Japan',74.21],
            ['Maychan', 16, 'New York', 'US',99.63],
            ['Mike', 17, 'las vegas', 'US',47.28]]
 
# Create a DataFrame object
df = pd.DataFrame(students,
                      columns=['Name', 'Age', 'City', 'Country','Agg_Marks'],
                           index=['a', 'b', 'c', 'd', 'e', 'f'])
 
# here we set Float column 'Agg_Marks' as index of data frame
# using dataframe.set_index() function
df = df.set_index('Agg_Marks')
 
 
# Displaying the Data frame
df


Output :

            Name  Age        City    Country
Agg_Marks                                   
85.96       jack   34      Sydeny  Australia
95.20       Riti   30       Delhi      India
85.25      Vansh   31       Delhi      India
74.21      Nanyu   32       Tokyo      Japan
99.63    Maychan   16    New York         US
47.28       Mike   17  las vegas         US

In the above example, we set the column ‘Agg_Marks‘ as an index of the data frame.

Pandas Dataframe Index Setting three columns as MultiIndex

In this example the below code utilizes Pandas to create a DataFrame ‘df’ from student data, with columns ‘Name’, ‘Age’, ‘City’, ‘Country’, ‘Agg_Marks’, and ‘ID’. It employs the `set_index()` function to establish a multi-level index using ‘Name’, ‘City’, and ‘ID’, and then displays the resulting DataFrame.

Python3




# importing pandas library
import pandas as pd
 
# creating and initializing a nested list
students = [['jack', 34, 'Sydeny', 'Australia',85.96,400],
            ['Riti', 30, 'Delhi', 'India',95.20,750],
            ['Vansh', 31, 'Delhi', 'India',85.25,101],
            ['Nanyu', 32, 'Tokyo', 'Japan',74.21,900],
            ['Maychan', 16, 'New York', 'US',99.63,420],
            ['Mike', 17, 'las vegas', 'US',47.28,555]]
 
# Create a DataFrame object
df = pd.DataFrame(students,
                      columns=['Name', 'Age', 'City', 'Country','Agg_Marks','ID'],
                           index=['a', 'b', 'c', 'd', 'e', 'f'])
 
# Here we pass list of 3 columns i.e 'Name', 'City' and 'ID'
# to dataframe.set_index() function
# to set them as multiIndex of dataframe
df = df.set_index(['Name','City','ID'])
 
 
# Displaying the Data frame
df


Output :

                    Age    Country  Agg_Marks
Name    City       ID                       
jack    Sydeny     400  34  Australia      85.96
Riti    Delhi      750  30      India      95.20
Vansh   Delhi      101  31      India      85.25
Nanyu   Tokyo      900  32      Japan      74.21
Maychan New York   420  16         US      99.63
Mike    las vegas  555  17         US      47.28

In the above example, we set the columns ‘Name‘, ‘City‘, and ‘ID‘ as multiIndex of the data frame.

Pandas Set Index of Specific Column

In this example the below code demonstrates how to use Pandas to create a DataFrame, set a specific column (‘Name’ in this case) as the index using the set_index() method, and then displays both the original and modified DataFrames. The inplace=True parameter ensures that the changes are applied directly to the DataFrame without the need for reassignment.

Python3




import pandas as pd
 
# Creating a sample DataFrame
data = {'Name': ['Geek1', 'Geek2', 'Geek3'],
        'Age': [25, 30, 35],
        'City': ['New York', 'San Francisco', 'Los Angeles']}
 
df = pd.DataFrame(data)
 
# Displaying the original DataFrame
print("Original DataFrame:")
print(df)
 
# Using set_index() to set 'Name' column as the index
df.set_index('Name', inplace=True)
 
# Displaying the DataFrame after setting the index
print("\nDataFrame after set_index:")
print(df)


Output :

Original DataFrame:
   Name  Age           City
0  Geek1   25       New York
1  Geek2   30  San Francisco
2  Geek3   35    Los Angeles
DataFrame after set_index:
      Age           City
Name                    
Geek1   25       New York
Geek2   30  San Francisco
Geek3   35    Los Angeles



Previous Article
Next Article

Similar Reads

Python | Pandas DataFrame.fillna() to replace Null values in dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and rem
5 min read
Difference Between Spark DataFrame and Pandas DataFrame
Dataframe represents a table of data with rows and columns, Dataframe concepts never change in any Programming language, however, Spark Dataframe and Pandas Dataframe are quite different. In this article, we are going to see the difference between Spark dataframe and Pandas Dataframe. Pandas DataFrame Pandas is an open-source Python library based o
3 min read
Pandas Dataframe.to_numpy() - Convert dataframe to Numpy array
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of the DataFrame.to_numpy() method. In this article we will see how to convert dataframe to numpy array. Syntax of Pandas DataFrame.to_numpy()
3 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to Convert Wide Dataframe to Tidy Dataframe with Pandas stack()?
We might sometimes need a tidy/long-form of data for data analysis. So, in python's library Pandas there are a few ways to reshape a dataframe which is in wide form into a dataframe in long/tidy form. Here, we will discuss converting data from a wide form into a long-form using the pandas function stack(). stack() mainly stacks the specified index
4 min read
Replace values of a DataFrame with the value of another DataFrame in Pandas
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.
4 min read
Converting Pandas Dataframe To Dask Dataframe
In this article, we will delve into the process of converting a Pandas DataFrame to a Dask DataFrame in Python through several straightforward methods. This conversion is particularly crucial when dealing with large datasets, as Dask provides parallel and distributed computing capabilities, allowing for efficient handling of substantial data volume
3 min read
Pandas Dataframe rank() | Rank DataFrame Entries
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas DataFrame rank() method returns a rank of every respective entry (1 through n) along an axis of the DataFrame passed. The rank is retu
3 min read
Pandas DataFrame to_dict() Method | Convert DataFrame to Dictionary
Python is a great language for doing data analysis because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas .to_dict() method is used to convert a DataFrame into a dictionary of series or list-like data type depending on the orient parameter. Exam
3 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
4 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
Filter Pandas dataframe in Python using 'in' and 'not in'
The in and not in operators can be used with Pandas DataFrames to check if a given value or set of values is present in the DataFrame or not using Python. The in-operator returns a boolean value indicating whether the specified value is present in the DataFrame, while the not-in-operator returns a boolean value indicating whether the specified valu
3 min read
Python | Pandas DataFrame.reset_index()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas reset_index() is a method to reset index of a Data Frame. reset_index() method sets a list of integer ranging from 0 to length of
2 min read
Python | Pandas dataframe.notna()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.notna() function detects existing/ non-missing values in the dataframe. The function returns a boolean object having the
2 min read
Python | Pandas dataframe.notnull()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.notnull() function detects existing/ non-missing values in the dataframe. The function returns a boolean object having t
2 min read
Python | Pandas dataframe.reindex_like()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.reindex_like() function return an object with matching indices to myself. Any non-matching indexes are filled with NaN
3 min read
Python | Pandas Dataframe.sort_values() | Set-2
Prerequisite: Pandas DataFrame.sort_values() | Set-1 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier. Pandas sort_values() function sorts a data frame in Ascending or Descending order
3 min read
Python | Pandas Dataframe.sample()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas sample() is used to generate a sample random row or column from the function caller data frame. Syntax: DataFrame.sample(n=None,
2 min read
Python | Pandas DataFrame.nlargest()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas nlargest() method is used to get n largest values from a data frame or a series. Syntax: DataFrame.nlargest(n, columns, keep='fir
2 min read
Python | Pandas DataFrame.nsmallest()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas nsmallest() method is used to get n least values from a data frame or a series. Syntax: DataFrame.nsmallest(n, columns, keep='firs
2 min read
Python | Pandas Dataframe.pop()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas Pop() method is common in most of the data structures but pop() method is a little bit different from the rest. In a stack, pop do
2 min read
Python | Pandas Dataframe.rename()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas rename() method is used to rename any index, column or row. Renaming of column can also be done by dataframe.columns = [#list]. B
3 min read
Python | Pandas dataframe.skew()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.skew() function return unbiased skew over requested axis Normalized by N-1. Skewness is a measure of the asymmetry of t
2 min read
Python | Pandas Categorical DataFrame creation
pandas.DataFrame(dtype="category") : For creating a categorical dataframe, dataframe() method has dtype attribute set to category. All the columns in data-frame can be converted to categorical either during or after construction by specifying dtype="category" in the DataFrame constructor. Code : # Python code explaining # constructing categorical d
1 min read
Python | Pandas Dataframe/Series.head() method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas head() method is used to return top n (5 by default) rows of a data frame or series. Syntax: Dataframe.head(n=5) Parameters: n: i
2 min read
Python | Pandas Dataframe/Series.tail() method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas tail() method is used to return bottom n (5 by default) rows of a data frame or series. Syntax: Dataframe.tail(n=5) Parameters: n
2 min read
Python | Pandas dataframe.subtract()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.subtract() function is used for finding the subtraction of dataframe and other, element-wise. This function is essentia
2 min read