Pandas Series.sort_values()
function is used to sort values on Series object. It sorts the series in ascending order or descending order, by default it does in ascending order. You can specify your preference using the ascending
parameter which is True
by default. In this article, you can find out how to sort values in pandas series with multiple examples.
Key Points –
Series.sort_values()
is a Pandas method that allows you to sort the values of a Pandas Series in ascending or descending order.Series.sort_values()
supports the use of a custom sorting criteria through thekey
parameter. This allows you to define a function that determines the sorting order based on specific conditions or transformations of the values.- By default, the method sorts the Series in ascending order. This means that the smallest values will be at the beginning of the Series.
- The method has an optional parameter
inplace
that, when set toTrue
, modifies the original Series in place. Otherwise, it returns a new sorted Series without modifying the original. - The method provides options to control the treatment of NaN (Not a Number) values during sorting. You can specify whether NaN values should be placed at the beginning or end of the sorted Series.
- Apart from sorting by values, the method also allows sorting based on the index of the Series, providing flexibility in arranging data based on both values and index.
1. Quick Examples of Sort Pandas Series
If you are in hurry below are some quick examples of how to sort values of DataFrame by using Series.sort_values().
# Quick examples of sort series
# Sort pandas Series in an ascending order
sortedSeries = mySeries.sort_values()
sortedSeries = mySeries.sort_values(ascending=True)
# Sort pandas Series in a descending order
sortedSeries = mySeries.sort_values(ascending=False)
# Sort inplace
mySeries.sort_values(ascending=False, inplace=True)
# Sort Series Contains Numeric Values
import pandas as pd
mySeries = pd.Series([25000,30000,23000,15000,80000])
mySeries.sort_values(ascending=True)
# Sort Series which contains NAN Values
# Keeping NaN as first. By default it puts at last
sortedSeries = Series.sort_values(ascending=True, na_position='first')
print(sortedSeries)
2. Syntax of Series.sort_values()
Following is the syntax of the Series.sort_values(). This takes params axis
, ascending
, inplace
, kind
and na_position
and returns a sorted Series object. With inplace=True
param it returns None.
# Syntax of Series.sort_values()
Series.sort_values(axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)
axis
– The axis along which the sorting will be done (0 for rows, 1 for columns).ascending
– A boolean or list of booleans indicating whether to sort in ascending order (default) or descending order.inplace
– A boolean indicating whether to perform the sorting in-place or return a new sorted Series.kind
– The sorting algorithm to be used (‘quicksort’, ‘mergesort’, ‘heapsort’, or ‘stable’).na_position
– Specifies the placement of NaN values during sorting (‘first’ or ‘last’).ignore_index
– If True, the resulting Series will have a new index.key
– A function that will be used to extract a comparable key from each element for custom sorting.
Now, Let’s create a pandas series.
# Create a pandas series.
import pandas as pd
series = pd.Series(['JAVA','PySpark','Spark','Hadoop'])
print(series)
Yields below output.
# Output:
0 Spark
1 PySpark
2 JAVA
3 Hadoop
dtype: object
3. 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. You can change this behavior by using na_position
param.
# Sort the series in ascending order.
sortedseries = series.sort_values()
(or)
sortedseries = series.sort_values(ascending=True)
print(sortedseries)
Yields below output.
# Output:
3 Hadoop
0 JAVA
1 PySpark
2 Spark
dtype: object
Note that the sort_values()
function returns a sorted copy of the original series. To modify the original series in-place, pass inplace=True
to the function.
# Sort the series in ascending order.
series.sort_values(inplace=True)
(or)
series.sort_values(ascending=True,inplace=True)
4. Sort Series in Descending Order
To sort a Pandas Series in descending order, you can use the Series.sort_values()
method with the ascending
parameter set to False
.
# Sort series in descending order.
sortedseries = series.sort_values(ascending=False)
print(sortedseries)
In this example, ascending=False
is used to sort the Series in descending order. The resulting sorted_series_desc
will have the values sorted from the largest to the smallest. This example yields the below output.
# Output:
2 Spark
1 PySpark
0 JAVA
3 Hadoop
dtype: object
5. Sort Series that Contains Numeric Values
Let’s now see how to sort a Series that includes numeric values. Now, create the following Pandas Series that contains only numeric values.
# Sort Series Contains Numeric Values.
import pandas as pd
series = pd.Series([25000,30000,23000,15000,80000])
print(series)
Now, to sort a Pandas Series that contains numeric values, you can use the Series.sort_values()
method. For instance, the sort_values()
method is used to sort the series
. The default behavior is to sort in ascending order, and you can set ascending=False
to sort in descending order.
# Sort the Series in an ascending order.
sortedSeries = Series.sort_values(ascending=True)
print(sortedSeries)
Yields below output.
# Output:
3 15000
2 23000
0 25000
1 30000
4 80000
dtype: int64
6. Sort Series Which Contains NaN Values
Now, let’s create a Series with NaN values using the Numpy
library and then place the NaN values at the last while the other values will be sorted in ascending order. By default, it places all NaN values at the last.
import pandas as pd
import numpy as np
# Create Series with NaN values
Series = pd.Series([25000,np.NaN,23000,15000,80000])
print(Series)
# Sort Series which contains NAN Values.
sortedSeries = Series.sort_values(ascending=True)
print(sortedSeries)
Yields below output.
# Output:
3 15000.0
2 23000.0
0 25000.0
4 80000.0
1 NaN
dtype: float64
Similarly, you can use the na_position
parameter to control the placement of NaN values during sorting. If you want to place NaN values at the beginning when sorting in descending order, you can set na_position='first'
.
# Sort the Series by keeping NaN as first
sortedSeries = Series.sort_values(ascending=True, na_position='first')
print(sortedSeries)
In the above example, na_position='first'
ensures that NaN values are placed at the beginning of the sorted Series when sorting in descending order. This example yields the below output.
# Output:
1 NaN
3 15000.0
2 23000.0
0 25000.0
4 80000.0
dtype: float64
7. Complete Examples to Sort Series Contains NAN Values
# Sort pandas Series in an ascending order:
sortedSeries = mySeries.sort_values()
sortedSeries = mySeries.sort_values(ascending=True)
# Sort pandas Series in a descending order.
sortedSeries = mySeries.sort_values(ascending=False)
# Sort inplace
mySeries.sort_values(ascending=False, inplace=True)
# Sort Series Contains Numeric Values.
import pandas as pd
mySeries = pd.Series([25000,30000,23000,15000,80000])
mySeries.sort_values(ascending=True)
# Sort Series which contains NAN Values.
# Keeping NaN as first. By default it puts at last
sortedSeries = Series.sort_values(ascending=True, na_position='first')
print(sortedSeries)
Frequently Asked Questions on Pandas Series.sort_values()
The Series.sort_values()
method in Pandas is used to sort the values of a Series in either ascending or descending order. It allows for flexible data manipulation and exploration by arranging values according to user-specified criteria.
By default, Series.sort_values()
performs stable sorting. In case of ties (equal values), the original order of those tied elements is preserved in the result. This ensures that the sorting operation is deterministic and reproducible.
Series.sort_values()
can be used with both numeric and non-numeric data. It is a versatile method that can handle sorting based on any comparable data type, including strings, dates, or custom objects, depending on the data contained in the Series.
Series.sort_values()
provides the inplace
parameter. If inplace
is set to False
(the default), a new sorted Series is returned, leaving the original Series unchanged. Setting inplace=True
modifies the original Series in place.
The na_position
parameter specifies the placement of NaN (Not a Number) values during sorting. It can be set to ‘first’ to place NaN values at the beginning of the sorted Series or ‘last’ to place them at the end. The default is ‘last’.
The method provides the key
parameter, allowing you to specify a custom sorting function. This function is applied to each element in the Series, and the values are sorted based on the results of this function rather than the raw values themselves.
Conclusion
In this article, you have learned how to sort values in pandas series by using Series.sort_values()
It sorts the series in ascending order or descending order. By default, it does in ascending order and places all NaN values at the last.
Related Articles
- Filter Rows with NAN Value from Pandas DataFrame Column
- Pandas Series unique() Function with Examples
- How to Print Pandas DataFrame without Index
- Rename Index Values of Pandas DataFrame
- Rename Index of Pandas DataFrame
- Pandas Series.max() Function
- Pandas Series sum() Function
- How to Convert pandas Series to DataFrame
- How to Convert NumPy Array to Pandas Series?
- How to Get the Length of a Series in Pandas?
- Pandas Sort by Column Values DataFrame
- Pandas Series groupby() Function with Examples
- pandas DataFrame.sort_index() – Sort by Index
- Pandas Groupby Sort within Groups
- How to Sort Multiple Columns in Pandas DataFrame