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.)
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.
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.
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.
Use reindex
:
In [52]:
s = s.reindex(index = ['B','A','C'])
s
Out[52]:
B 2
A 1
C 3
dtype: int64
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With