Python 如何更改熊猫数据框中的单个索引值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40427943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i change a single index value in pandas dataframe?
提问by user517696
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?
我想将索引的值从“大韩民国”更改为“韩国”。但是数据框太大,不可能改变每个索引值。如何仅更改此单个值?
回答by Batman
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.
基本上,您将索引作为列表,更改该元素,然后替换现有索引。
回答by ErnestScribbler
@EdChum's solution looks good. Here's one using rename, which would replace all these values in the index.
@EdChum 的解决方案看起来不错。这是一个使用重命名的方法,它将替换索引中的所有这些值。
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
回答by Andrea C
回答by S.V
If you have MultiIndex DataFrame, do this:
如果您有 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)
回答by Andrea C
Here's another idea based on set_value
这是基于的另一个想法 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
回答by Abdul Rafay
Try This
尝试这个
df.rename(index={'Republic of Korea':'South Korea'},inplace=True)
回答by mpeli
This seems to work too:
这似乎也有效:
energy.index.values[energy.index.tolist().index('Republic of Korea')] = 'South Korea'
No idea though whether this is recommended or discouraged.
不知道这是推荐还是不鼓励。