How do i change a single index value in pandas dat

2020-02-02 07:51发布

energy.loc['Republic of Korea']

I want to change the value of index from 'Republic of Korea' to 'South Korea'. But the dataframe is too large and it is not possible to change every index value. How do i change only this single value?

6条回答
叛逆
2楼-- · 2020-02-02 08:31

If you have MultiIndex DataFrame, do this:

# input DataFrame
import pandas as pd
t = pd.DataFrame(data={'i1':[0,0,0,0,1,1,1,1,2,2,2,2],
                       'i2':[0,1,2,3,0,1,2,3,0,1,2,3],
                       'x':[1.,2.,3.,4.,5.,6.,7.,8.,9.,10.,11.,12.]})
t.set_index(['i1','i2'], inplace=True)
t.sort_index(inplace=True)

# changes index level 'i1' values 0 to -1
t.rename(index={0:-1}, level='i1', inplace=True)
查看更多
欢心
3楼-- · 2020-02-02 08:33

Here's another idea based on set_value

df = df.reset_index()
df.drop('index', axis = 1, inplace=True)
index = df.index[df["Country"] == "Republic of Korea"]
df.set_value(index, "Country", "South Korea")
df = df.set_index("Country")
df["Country"] = df.index
查看更多
Lonely孤独者°
4楼-- · 2020-02-02 08:42

Here's another good one, using replace on the column.

df.reset_index(inplace=True)
df.drop('index', axis = 1, inplace=True)
df["Country"].replace("Republic of Korea", value="South Korea", inplace=True)
df.set_index("Country", inplace=True)
查看更多
Viruses.
5楼-- · 2020-02-02 08:52

@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 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
查看更多
放我归山
6楼-- · 2020-02-02 08:56

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.

查看更多
再贱就再见
7楼-- · 2020-02-02 08:58

Try This

df.rename(index={'Republic of Korea':'South Korea'},inplace=True)
查看更多
登录 后发表回答