pandas 系列:更改索引顺序 [英] pandas series: change order of index

查看:35
本文介绍了 pandas 系列:更改索引顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫系列,例如这样

I have a Pandas series, for example like this

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

如何改变索引的顺序,让s变成

How can I change the order of the index, so that s becomes

B    2
A    1
C    3

我试过了

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

推荐答案

使用 reindex:

In [52]:

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

这篇关于 pandas 系列:更改索引顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆