w3resource

Pandas Data Series: Change the order of index of a given series

Pandas: Data Series Exercise-14 with Solution

Write a Pandas program to change the order of index of a given series.

Sample Solution :

Python Code :

import pandas as pd
s = pd.Series(data = [1,2,3,4,5], index = ['A', 'B', 'C','D','E'])
print("Original Data Series:")
print(s)
s = s.reindex(index = ['B','A','C','D','E'])
print("Data Series after changing the order of index:")
print(s)

Sample Output:

Original Data Series:
A    1
B    2
C    3
D    4
E    5
dtype: int64
Data Series after changing the order of index:
B    2
A    1
C    3
D    4
E    5
dtype: int64                   

Explanation:

In the above exercise -

s = pd.Series(data = [1,2,3,4,5], index = ['A', 'B', 'C','D','E']): This code creates a Pandas Series object 's' containing a sequence of five integer values and assigns custom index labels to each value. The index labels are ['A', 'B', 'C', 'D', 'E'] and the corresponding values are [1, 2, 3, 4, 5].

s = s.reindex(index = ['B','A','C','D','E']); This code creates a new Pandas Series object 's' by reindexing the original Series object 's' based on a new index list ['B', 'A', 'C', 'D', 'E'] using the .reindex() method. The resulting Series object 's' will have the same values as the original Series object 's', but with the index labels in the order specified by the new index list.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to create a subset of a given series based on value and condition.
Next: Write a Pandas program to create the mean and standard deviation of the data of a given Series.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.