pandas 熊猫系列:更改索引顺序

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

pandas series: change order of index

pythonpandas

提问by Anne

I have a Pandas series, for example like this

我有一个Pandas系列,例如这样

s = pandas.Series(data = [1,2,3], index = ['A', 'B', 'C'])

How can I change the order of the index, so that sbecomes

如何更改索引的顺序,使其s变为

B    2
A    1
C    3

I have tried

我试过了

s['B','A','C']

but that will give me a key error. (In this particular example I could presumably take care of the order of the index while constructing the series, but I would like to have a way to do this after the series has been created.)

但这会给我一个关键错误。(在这个特定示例中,我大概可以在构建系列时处理索引的顺序,但我希望在创建系列后有办法做到这一点。)

回答by EdChum

Use reindex:

使用reindex

In [52]:

s = s.reindex(index = ['B','A','C'])
s
Out[52]:
B    2
A    1
C    3
dtype: int64