w3resource

Pandas Data Series: Sort a given Series


Write a Pandas program to sort a given Series.

Sample Solution :

Python Code :

import pandas as pd
s = pd.Series(['100', '200', 'python', '300.12', '400'])
print("Original Data Series:")
print(s)
new_s = pd.Series(s).sort_values()
print(new_s)

Sample Output:

Original Data Series:
0       100
1       200
2    python
3    300.12
4       400
dtype: object
0       100
1       200
3    300.12
4       400
2    python
dtype: object                     

Explanation:

In the above exercise -

s = pd.Series(['100', '200', 'python', '300.12', '400']): This code creates a Pandas Series object 's' containing a sequence of five string values: ['100', '200', 'python', '300.12', '400'].

new_s = pd.Series(s).sort_values(): This line creates a new Pandas Series object 'new_s' by passing the original Series object 's' to the pd.Series() constructor and sorting the resulting Series object using the .sort_values() method.

The resulting Series object 'new_s' will have the same values as the original Series object 's', but sorted in ascending order based on their values.

Python-Pandas Code Editor:

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

Previous: Write a Pandas program to convert Series of lists to one Series.
Next: Write a Pandas program to add some data to an existing 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.