Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas series: change order of index

Tags:

python

pandas

I have a Pandas series, for example like this

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

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

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

like image 870
Anne Avatar asked May 13 '15 10:05

Anne


People also ask

How do I change the order of indexes in series?

Suppose we want to change the order of the index of series, then we have to use the Series. reindex() Method of pandas module for performing this task. Series, which is a 1-D labeled array capable of holding any data.

Can you change the index of a pandas series?

It is possible to specify or change the index labels of a pandas Series object after creation also. It can be done by using the index attribute of the pandas series constructor.

How do I order a pandas series?

Sort the Series in Ascending Order By default, the pandas series sort_values() function sorts the series in ascending order. You can also use ascending=True param to explicitly specify to sort in ascending order. Also, if you have any NaN values in the Series, it sort by placing all NaN values at the end.


1 Answers

Use reindex:

In [52]:

s = s.reindex(index = ['B','A','C'])
s
Out[52]:
B    2
A    1
C    3
dtype: int64
like image 165
EdChum Avatar answered Sep 21 '22 21:09

EdChum