close

How do I change a single index value in pandas dataframe?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I change a single index value in pandas dataframe in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do I change a single index value in pandas dataframe?

  1. How do I change a single index value in pandas dataframe?

    Here's one using rename, which would replace all these values in the index.
    energy.rename(index={'Republic of Korea':'South Korea'},inplace=True)

  2. change a single index value in pandas dataframe

    Here's one using rename, which would replace all these values in the index.
    energy.rename(index={'Republic of Korea':'South Korea'},inplace=True)

Method 1

Here’s one using rename, which would replace all these values in the index.

energy.rename(index={'Republic of Korea':'South Korea'},inplace=True)

Here’s an example

>>> example = pd.DataFrame({'key1' : ['a','a','a','b','a','b'],
           'data1' : [1,2,2,3,nan,4],
           'data2' : list('abcdef')})
>>> example.set_index('key1',inplace=True)
>>> example
      data1 data2
key1             
a       1.0     a
a       2.0     b
a       2.0     c
b       3.0     d
a       NaN     e
b       4.0     f

>>> example.rename(index={'a':'c'}) # can also use inplace=True
      data1 data2
key1             
c       1.0     a
c       2.0     b
c       2.0     c
b       3.0     d
c       NaN     e
b       4.0     f

Method 2

You want to do something like this:

as_list = df.index.tolist()
idx = as_list.index('Republic of Korea')
as_list[idx] = 'South Korea'
df.index = as_list

Basically, you get the index as a list, change that one element, and the replace the existing index.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read