Pandas series is a great tool for handling sequential data in python. In this article, we will discuss different ways to check if a pandas series is sorted.
Check if a Pandas Series Is Sorted Using the is_monotonic Attribute
To check if a pandas series is sorted in ascending order, we can use the is_monotonic
attribute of the series. The is_monotonic
attribute evaluates to True if a pandas series is sorted in either ascending order.
For instance, if a series is sorted in ascending order, the is_monotonic
attribute will evaluate to True as shown below.
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic)
Output:
The series is:
2 -100
5 -3
0 3
3 14
4 16
1 23
6 45
7 65
dtype: int64
The series is sorted?:
True
In the above example, we first created a Series using the Series()
constructor. Then, we sorted the series using the sort_values()
method. After this, we invoked the is_monotonic
attribute on the series. You can observe that the is_monotonic
attribute evaluates to True when invoked on a sorted series in ascending order.
If a series is sorted in descending order, the is_monotonic
attribute will evaluate to False.
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,ascending=False)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic)
Output:
The series is:
7 65
6 45
1 23
4 16
3 14
0 3
5 -3
2 -100
dtype: int64
The series is sorted?:
False
In this example, we have set the ascending
parameter to False in the sort_values()
method. Due to this, the series is sorted in descending order. When we invoked the is_monotonic
attribute on the series which is sorted in descending order, it evaluates to False.
If a pandas series is not sorted, the is_monotonic
attribute will evaluate as False. You can observe this in the following example.
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic)
Output:
The series is:
0 3
1 23
2 -100
3 14
4 16
5 -3
6 45
7 65
dtype: int64
The series is sorted?:
False
In the above example, we haven’t sorted the series. Hence, the is_monotonic
attribute evaluates to False.
The is_monotonic
attribute doesn’t work with NaN values. If a series contains NaN values, the is_monotonic
attribute always evaluates to False. You can observe this in the following example.
import pandas as pd
import numpy as np
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic)
Output:
The series is:
0 3.0
3 14.0
4 16.0
1 23.0
6 45.0
7 65.0
2 NaN
5 NaN
dtype: float64
The series is sorted?:
False
In the above example, we have created a series having NaN values. Then, we sorted the series in ascending order. When the is_monotonic
attribute is invoked on a sorted series with NaN values, it evaluates to False as shown in the output. One might argue that the NaN values in the sorted series are at the bottom. That’s why the is_monotonic
attribute evaluates to False.
However, even if we put the NaN values at the top of the pandas series, the is_monotonic
attribute will evaluate to False as shown below.
import pandas as pd
import numpy as np
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,na_position="first")
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic)
Output:
The series is:
2 NaN
5 NaN
0 3.0
3 14.0
4 16.0
1 23.0
6 45.0
7 65.0
dtype: float64
The series is sorted?:
False
In the above example, the NaN values are present at the top of the sorted series. Even after this, the is_monotonic
attribute evaluates to False.
While using the is_monotonic
attribute, you will get a FutureWarning with the message “FutureWarning: is_monotonic is deprecated and will be removed in a future version. Use is_monotonic_increasing instead.” It means that the is_monotonic
attribute will be deprecated in future pandas versions. As an alternative, we can use the is_monotonic_increasing
and is_monotonic_decreasing
attributes to check if a pandas series is sorted in python.
Check if a Pandas Series Is Sorted in Ascending Order
To check if a pandas series is sorted in ascending order, we can use the is_monotonic_increasing
attribute. The is_monotonic_increasing
attribute evaluates to True if a series is sorted in ascending order. Otherwise, it is set to False. You can observe this in the following example.
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_increasing)
Output:
The series is:
2 -100
5 -3
0 3
3 14
4 16
1 23
6 45
7 65
dtype: int64
The series is sorted?:
True
In the above example, we have used the is_monotonic_increasing
attribute to check if the series is sorted. As we have sorted the series in ascending order, the is_monotonic_increasing
attribute evaluates to True.
If a series is not sorted in ascending order, the is_monotonic_increasing
attribute evaluates to False.
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_increasing)
Output:
The series is:
0 3
1 23
2 -100
3 14
4 16
5 -3
6 45
7 65
dtype: int64
The series is sorted?:
False
In the above example, we haven’t sorted the input series. Hence, the is_monotonic_increasing
attribute evaluates to False when invoked on the series object.
Also, if a pandas series is sorted in descending order, the is_monotonic_increasing
attribute evaluates to False.
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,ascending=False)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_increasing)
Output:
The series is:
7 65
6 45
1 23
4 16
3 14
0 3
5 -3
2 -100
dtype: int64
The series is sorted?:
False
In this example, the series is sorted in descending order. Hence, the is_monotonic_increasing
attribute evaluates to False.
The is_monotonic_increasing
cannot be used with series objects having NaN values. The is_monotonic_increasing
attribute always evaluates to False if a pandas series has NaN values. You can observe this in the following example.
import pandas as pd
import numpy as np
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_increasing)
Output:
The series is:
0 3.0
3 14.0
4 16.0
1 23.0
6 45.0
7 65.0
2 NaN
5 NaN
dtype: float64
The series is sorted?:
False
In the above example, we have created a series having NaN values. Then, we sorted the series in ascending order. When the is_monotonic_increasing
attribute is invoked on a sorted series with NaN values, it evaluates to False as shown in the output. One might argue that the NaN values in the sorted series are at the bottom. That’s why the is_monotonic_increasing
attribute evaluates to False.
Even if we put the NaN values at the top of the series, the is_monotonic_increasing
attribute will evaluate to False.
import pandas as pd
import numpy as np
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,na_position="first")
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_increasing)
Output:
The series is:
2 NaN
5 NaN
0 3.0
3 14.0
4 16.0
1 23.0
6 45.0
7 65.0
dtype: float64
The series is sorted?:
False
In this example, the NaN values are put at the top of the sorted series. Even after this, the is_monotonic_increasing
attribute evaluates to False. It shows that the is_monotonic_increasing
attribute doesn’t work with NaN values.
Interesting read: Command line arguments in Python
Check if a Series Is Sorted in Descending Order in Python
To check if a pandas series is sorted in descending order, we will use the is_monotonic_decreasing
attribute. The is_monotonic_decreasing
attribute evaluates to True if a series is sorted in descending order. You can observe this in the following example.
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,ascending=False)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_decreasing)
Output:
The series is:
7 65
6 45
1 23
4 16
3 14
0 3
5 -3
2 -100
dtype: int64
The series is sorted?:
True
In the above example, we have used the is_monotonic_decreasing
attribute to check if the series is sorted in descending order. As we have sorted the series in ascending order, the is_monotonic_decreasing
attribute evaluates to True.
If a series is unsorted or is sorted in ascending order, the is_monotonic_decreasing
attribute evaluates to False as shown below.
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_decreasing)
Output:
The series is:
0 3
1 23
2 -100
3 14
4 16
5 -3
6 45
7 65
dtype: int64
The series is sorted?:
False
In the above example, the is_monotonic_decreasing
attribute is invoked on an unsorted series. Hence, it evaluates to False.
The is_monotonic_decreasing
attribute cannot be used with series objects having NaN values. The is_monotonic_decreasing
attribute always evaluates to False if a pandas series has NaN values. You can observe this in the following example.
import pandas as pd
import numpy as np
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,ascending=False)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_decreasing)
Output:
The series is:
7 65.0
6 45.0
1 23.0
4 16.0
3 14.0
0 3.0
2 NaN
5 NaN
dtype: float64
The series is sorted?:
False
In the above example, we have created a series having NaN values. Then, we sorted the series in descending order. When the is_monotonic_decreasing
attribute is invoked on a sorted series with NaN values, it evaluates to False as shown in the output. One might argue that the NaN values in the sorted series are at the bottom. That’s why the is_monotonic_decreasing
attribute evaluates to False.
However, even if we put the NaN values at the top of the series, the is_monotonic_decreasing
attribute will evaluate to False.
import pandas as pd
import numpy as np
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,ascending=False,na_position="first")
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_decreasing)
Output:
The series is:
2 NaN
5 NaN
7 65.0
6 45.0
1 23.0
4 16.0
3 14.0
0 3.0
dtype: float64
The series is sorted?:
False
In this example, we have put the NaN values at the top of the sorted series. Even after that, the is_monotonic_decreasing
attribute evaluates to False. It confirms that we can use the is_monotonic_decreasing
with series having NaN values.
Suggested Reading: If you are into machine learning, you can read this MLFlow tutorial with code examples. You might also like this article on clustering mixed data types in Python.
Check if A Series Is Sorted Using the Numpy Module
The numpy module in python provides us with different functions to perform operations on numeric data. One such function is the diff()
function. The diff()
function takes an iterable object like a series as its input argument and returns an array containing the first-order difference of the array elements as shown in the following example.
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
print("The series is:")
print(series)
temp=np.diff(series)
print("Array returned by diff() is:")
print(temp)
Output:
The series is:
0 3
1 23
2 -100
3 14
4 16
5 -3
6 45
7 65
dtype: int64
Array returned by diff() is:
[ 20 -123 114 2 -19 48 20]
In the above example, we have passed the series to the diff()
function. You can observe that the elements in the list are differences of the elements in the series. For instance, the first element in the output list is the difference between the second and the first element in the series. Similarly, the second element in the output list is the difference between the third and second elements of the series.
Hence, you can observe that the first-order difference is calculated as the difference between (n+1)th and nth element in the input series.
To check if a pandas series is sorted in ascending order using the diff()
function, we will use the following steps.
- First, we will calculate the first-order difference of the pandas series. For this, we will pass the series to the
diff()
function as an input argument. - After that, we will check if all the elements in the output array are greater than or equal to 0. For this, we will use the comparison operator and the
all()
method. When we use the comparison operator on a numpy array, we get an array of boolean values. Theall()
method, when invoked on an array containing boolean values, returns True if all the elements are True. - If the
all()
method returns True, it will conclude that the pandas series is sorted in ascending order. You can observe this in the following example.
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series=series.sort_values()
print("The series is:")
print(series)
temp=np.diff(series)
boolean_array= temp>=0
print("Boolean array is:")
print(boolean_array)
result=boolean_array.all()
if result:
print("The series is sorted.")
else:
print("The series is not sorted.")
Output:
The series is:
2 -100
5 -3
0 3
3 14
4 16
1 23
6 45
7 65
dtype: int64
Boolean array is:
[ True True True True True True True]
The series is sorted.
To check if a pandas series is sorted in descending order, we will check if all the elements in the output array of the diff()
function are less than or equal to 0. For this, we will use the comparison operator and the all()
method. When we use the comparison operator on a numpy array, we get an array of boolean values. The all()
method, when invoked on an array containing boolean values, returns True if all the elements are True.
If the all()
method returns True, it will conclude that the pandas series is sorted in descending order. You can observe this in the following example.
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series=series.sort_values(ascending=False)
print("The series is:")
print(series)
temp=np.diff(series)
boolean_array= temp<=0
print("Boolean array is:")
print(boolean_array)
result=boolean_array.all()
if result:
print("The series is sorted.")
else:
print("The series is not sorted.")
Output:
The series is:
7 65
6 45
1 23
4 16
3 14
0 3
5 -3
2 -100
dtype: int64
Boolean array is:
[ True True True True True True True]
The series is sorted.
Check if the Index of a Series Is Sorted in Python
To check if the index of a pandas series is sorted, we can use the index
attribute and the is_monotonic
attribute as shown below.
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
sorted_series=series.sort_index()
print("The series is:")
print(sorted_series)
print("The index of series is sorted?:")
print(sorted_series.index.is_monotonic)
Output:
The series is:
2 abcd
3 a
11 c
14 ab
16 abc
23 b
45 bc
65 d
dtype: object
The index of series is sorted?:
True
To check if the index of a pandas series is sorted in ascending order, we can use the index
attribute and the is_monotonic_increasing
attribute as shown below.
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
sorted_series=series.sort_index()
print("The series is:")
print(sorted_series)
print("The index of series is sorted?:")
print(sorted_series.index.is_monotonic_increasing)
Output:
The series is:
2 abcd
3 a
11 c
14 ab
16 abc
23 b
45 bc
65 d
dtype: object
The index of series is sorted?:
True
To check if the index of a pandas series is sorted in descending order, we can use the index
attribute and the is_monotonic_decreasing
attribute as shown below.
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
sorted_series=series.sort_index(ascending=False)
print("The series is:")
print(sorted_series)
print("The index of series is sorted?:")
print(sorted_series.index.is_monotonic_decreasing)
Output:
The series is:
65 d
45 bc
23 b
16 abc
14 ab
11 c
3 a
2 abcd
dtype: object
The index of series is sorted?:
True
You need to keep in mind that the is_monotonic
attribute, is_monotonic_increasing
attribute, and the is_monotonic_decreasing
always return False if the index column contains NaN values. Therefore, you cannot use these attributes to check if the index is sorted if the index column contains NaN values.
Conclusion
In this article, we have discussed different ways to check if a pandas series is sorted. To know more about the pandas module, you can read this article on how to sort a pandas dataframe. You might also like this article on how to drop columns from a pandas dataframe.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.