如何更改 pandas 数据框中的单个索引值?

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

energy.loc['Republic of Korea']

我想将索引的值从 'Republic of Korea' 更改为 'South Korea'。 但是数据帧太大,不可能改变每个索引值。如何仅更改此单个值?

您想做这样的事情:

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

基本上,您获取列表形式的索引,更改其中一个元素,然后替换现有索引。

这是另一个基于 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

这是另一个很好的,在列上使用 replace

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)

@EdChum 的解决方案看起来不错。 这是一个使用重命名的方法,它将替换索引中的所有这些值。

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

这是一个例子

>>> 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

如果您有 MultiIndex DataFrame,请执行以下操作:

# 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)

试试这个

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

这似乎也有效:

energy.index.values[energy.index.tolist().index('Republic of Korea')] = 'South Korea'

不知道这是推荐还是不鼓励。

我们可以使用rename函数来改变行索引或列名。这是例子,

假设数据框如下所示,

       student_id     marks
index
  1        12          33
  2        23          98
  • 将索引 1 更改为 5

我们将使用 axis = 0 用于行

df.rename({ 1 : 5 }, axis=0)

df 指数据帧变量。所以,输出会像

       student_id     marks
index
  5        12          33
  2        23          98
  • 更改列名

我们将不得不使用 axis = 1

df.rename({ "marks" : "student_marks" }, axis=1)

所以,更改后的数据框是

       student_id     student_marks
index
  5        12              33
  2        23              98