How to rename index in Pandas

You can rename the index in Pandas with the following code. In this article, you’ll see the five examples with solutions that will be very helpful to rename the index. I highly recommend the “Python Crash Course Book” to learn Python.

Example 1: Rename multiple indices in Pandas

# Import the Pandas library as pd
import pandas as pd

# Create DataFrame
df = pd.DataFrame([[10, 12, 14, 16],[18, 20, 22, 24], [30, 40, 50, 60]])

# Display DataFrame
print(df)

# Rename index
df1 = df.set_axis(['A', 'B', 'C'], axis=0)

# Display New DataFrame
print(df1)

Output:

    0   1   2   3
0  10  12  14  16
1  18  20  22  24
2  30  40  50  60
    0   1   2   3
A  10  12  14  16
B  18  20  22  24
C  30  40  50  60

Example 2: Rename index with the date column

# Import the Pandas library as pd
import pandas as pd

# Read CSV File
df = pd.read_csv("weather.csv")

# Display First Five Rows
print(df.head())

# Rename index
df1 = df.set_index('date')

# Display New DataFrame
print(df1.head())

Output:

         date  min_temp  max_temp
0  01/01/2013      29.8      15.2
1  02/01/2013      32.1      16.8
2  03/01/2013      34.3      18.5
3  04/01/2013      33.1      17.6
4  05/01/2013      31.5      14.6
            min_temp  max_temp
date                          
01/01/2013      29.8      15.2
02/01/2013      32.1      16.8
03/01/2013      34.3      18.5
04/01/2013      33.1      17.6
05/01/2013      31.5      14.6

Example 3: Rename the single index of Pandas DataFrame

# Import the Pandas library as pd
import pandas as pd

# Create DataFrame
df = pd.DataFrame([[10, 12, 14, 16],[18, 20, 22, 24], [30, 40, 50, 60]])

# Display DataFrame
print(df)

# Rename index
df1 = df.rename(index={2: 'H'})

# Display New DataFrame
print(df1.head())

Output:

    0   1   2   3
0  10  12  14  16
1  18  20  22  24
2  30  40  50  60
    0   1   2   3
0  10  12  14  16
1  18  20  22  24
H  30  40  50  60

Example 4:

# Import the Pandas library as pd
import pandas as pd

# Create DataFrame
df = pd.DataFrame([[10, 12, 14, 16],[18, 20, 22, 24], [30, 40, 50, 60]])

# Display DataFrame
print(df)

# Rename index
df1 = df.set_axis(['A', 'B', 'C'], axis='index')

# Display New DataFrame
print(df1)

Output:

    0   1   2   3
0  10  12  14  16
1  18  20  22  24
2  30  40  50  60
    0   1   2   3
A  10  12  14  16
B  18  20  22  24
C  30  40  50  60

Example 5: Simple method to rename indices

# Import the Pandas library as pd
import pandas as pd

# Create DataFrame
df = pd.DataFrame([[10, 12, 14, 16],[18, 20, 22, 24], [30, 40, 50, 60]])

# Display DataFrame
print(df)

# Rename index
df1 = df.set_axis(['A', 'B', 'C'])

# Display New DataFrame
print(df1)

Output:

    0   1   2   3
0  10  12  14  16
1  18  20  22  24
2  30  40  50  60
    0   1   2   3
A  10  12  14  16
B  18  20  22  24
C  30  40  50  60

Leave a Comment

Your email address will not be published.