Sort a Pandas Series in Python
Last Updated :
05 Jul, 2021
Series is a one-dimensional labeled array capable of holding data of the type integer, string, float, python objects, etc. The axis labels are collectively called index.
Now, Let’s see a program to sort a Pandas Series.
For sorting a pandas series the Series.sort_values() method is used.
Syntax: Series.sort_values(axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)Sorted
Returns: Sorted series
Examples 1: Sorting a numeric series in ascending order.
Python3
import pandas as pd
s = pd.Series([ 100 , 200 , 54.67 ,
300.12 , 400 ])
s
|
Output:
Now we will use Series.sort_values() method to sort a numeric series in ascending order.
Python3
sorted_series = s.sort_values(ascending
= True )
sorted_series
|
Output:
From the output, we can see that the numeric series is sorted in ascending order.
Example 2: Sorting a numeric series in descending order.
Python3
import pandas as pd
s = pd.Series([ 100 , 200 , 54.67 ,
300.12 , 400 ])
s
|
Output:
Now we will use Series.sort_values() method to sort a numeric series in descending order.
Python3
sorted_series = s.sort_values(ascending
= False )
sorted_series
|
Output:
From the output, we can see that the numeric series is sorted in descending order.
Example 3: Sorting a series of strings.
Python3
import pandas as pd
s = pd.Series([ "OS" , "DBMS" , "DAA" ,
"TOC" , "ML" ])
s
|
Output:
Now we will use Series.sort_values() method to sort a series of strings.
Python3
sorted_series = s.sort_values(ascending
= True )
sorted_series
|
Output:
From the output, we can see that the string series is sorted in a lexicographically ascending order.
Example 4: Sorting values inplace.
Python3
import numpy as np
import pandas as pd
s = pd.Series([np.nan, 1 , 3 ,
10 , 5 ])
s
|
Output:
Now we will use Series.sort_values() method to sort values inplace
Python3
s.sort_values(ascending = False ,
inplace = True )
s
|
Output:
The output shows that the inplace sorting in the Pandas Series.
Example 5: Sorting values in the series by putting NaN first.
Python3
import numpy as np
import pandas as pd
s = pd.Series([np.nan, 1 , 3 ,
10 , 5 ])
s
|
Output:
Now we will use Series.sort_values() method to sort values in the series by putting NaN first.
Python3
sorted_series = s.sort_values(na_position =
'first' )
sorted_series
|
Output:
The output shows that the NaN (not a number) value is given the first place in the sorted series.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...