Setting the Index name for a DataFrame in pandas

python @ Freshers.in

In the pandas library, the DataFrame is a two-dimensional labeled data structure with columns that can be of different types. The index of a DataFrame helps in the quick retrieval of data and can be named for better understanding and clarity. In this article, we’ll explore how to set the index name for a DataFrame using various options.

DataFrame creation

Let’s start by creating a basic DataFrame

import pandas as pd
data = {
    'Name': ['Sachin', 'Rajesh', 'Dennis'],
    'Age': [25, 30, 35],
    'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
print(df)

Output

     Name  Age         City
0  Sachin   25     New York
1  Rajesh   30  Los Angeles
2  Dennis   35      Chicago

Setting the index name

To set the index name of a DataFrame, you can simply assign a string to the name attribute of the DataFrame’s index:

df.index.name = 'ID'
print(df)

The DataFrame now looks like:

      Name  Age         City
ID                          
0   Sachin   25     New York
1   Rajesh   30  Los Angeles
2   Dennis   35      Chicago

The index now has the name “ID”.

Setting index name while creating a dataframe

You can also set the index name directly when creating the DataFrame:

df = pd.DataFrame(data, index=pd.RangeIndex(start=0, stop=3, name='ID'))
print(df)

This produces the same result as the previous example.

      Name  Age         City
ID                          
0   Sachin   25     New York
1   Rajesh   30  Los Angeles
2   Dennis   35      Chicago

Resetting the index name

To reset or remove the index name, simply assign None to the name attribute of the index:

df.index.name = None
print(df)
     Name  Age         City
0  Sachin   25     New York
1  Rajesh   30  Los Angeles
2  Dennis   35      Chicago

Refer more on python here :

Author: user