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

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


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.


@EdChum's solution looks good.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 data2key1             a       1.0     aa       2.0     ba       2.0     cb       3.0     da       NaN     eb       4.0     f>>> example.rename(index={'a':'c'}) # can also use inplace=True      data1 data2key1             c       1.0     ac       2.0     bc       2.0     cb       3.0     dc       NaN     eb       4.0     f


Try This

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