如何更改 Pandas 数据框中的特定行标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42142756/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:56:32  来源:igfitidea点击:

How can I change a specific row label in a Pandas dataframe?

pythonpython-3.xpandasdataframelabel

提问by August Williams

I have a dataframe such as:

我有一个数据框,例如:

      0     1    2    3    4    5
0  41.0  22.0  9.0  4.0  2.0  1.0
1   6.0   1.0  2.0  1.0  1.0  1.0
2   4.0   2.0  4.0  1.0  0.0  1.0
3   1.0   2.0  1.0  1.0  1.0  1.0
4   5.0   1.0  0.0  1.0  0.0  1.0
5  11.4   5.6  3.2  1.6  0.8  1.0

Where the final row contains averages. I would like to rename the final row label to "A"so that the dataframe will look like this:

最后一行包含平均值。我想将最后一行标签重命名为,"A"以便数据框如下所示:

      0     1    2    3    4    5
0  41.0  22.0  9.0  4.0  2.0  1.0
1   6.0   1.0  2.0  1.0  1.0  1.0
2   4.0   2.0  4.0  1.0  0.0  1.0
3   1.0   2.0  1.0  1.0  1.0  1.0
4   5.0   1.0  0.0  1.0  0.0  1.0
A  11.4   5.6  3.2  1.6  0.8  1.0

I understand columns can be done with df.columns = . . .. But how can I do this with a specific row label?

我知道列可以用df.columns = . . .. 但是我如何使用特定的行标签来做到这一点?

回答by Vaishali

You can get the last index using negative indexing similar to that in Python

您可以使用类似于 Python 中的负索引来获取最后一个索引

last = df.index[-1]

Then

然后

df = df.rename(index={last: 'a'})

Edit: If you are looking for a one-liner,

编辑:如果您正在寻找单线,

df.index = df.index[:-1].tolist() + ['a']

回答by Boud

use indexattribute:

使用index属性:

 df.index = df.index[:-1].append(pd.Index(['A']))