Pandas Series.sort_values()
Pandas Series.sort_values() Tutorial
In this tutorial, we'll explore the Series.sort_values()
method in Pandas, which is used to sort the values of a Pandas Series in ascending or descending order, with well detailed examples.
The syntax of Series.sort_values(ascending=True, inplace=False, na_position='last')
is:
Series.sort_values(ascending=True, inplace=False, na_position='last')
where
Parameter | Description |
---|---|
ascending | Whether to sort in ascending (True) or descending (False) order. Default is True. |
inplace | Whether to perform the operation in-place or return a new Series. Default is False. |
na_position | Position of NaN values: 'first' or 'last'. Default is 'last'. |
The Series.sort_values()
method allows you to sort the values of a Series in either ascending or descending order.
Examples for Series.sort_values() function
1. Sort values in ascending order using Series.sort_values()
In this example, we'll use Series.sort_values()
to sort the values of a Pandas Series in ascending order.
Python Program
import pandas as pd
# Create a Series
original_series = pd.Series([30, 10, 20, 50, 40])
# Sort values in ascending order
sorted_series = original_series.sort_values()
# Print original and sorted Series
print("Original Series:")
print(original_series)
print("\nSorted Series (Ascending):")
print(sorted_series)
Output
Original Series:
0 30
1 10
2 20
3 50
4 40
dtype: int64
Sorted Series (Ascending):
1 10
2 20
0 30
4 40
3 50
dtype: int64
2. Sort values in descending order (In-Place)
In this example, we'll use Series.sort_values()
to sort the values of a Pandas Series in descending order, and we'll perform the sorting in-place.
To sort in descending order, pass the argument False
for ascending
parameter.
Python Program
import pandas as pd
# Create a Series
original_series = pd.Series([30, 10, 20, 50, 40])
# Sort values in descending order (In-Place)
original_series.sort_values(ascending=False, inplace=True)
# Print the sorted Series
print("Sorted Series (Descending - In-Place):")
print(original_series)
Output
Sorted Series (Descending - In-Place):
3 50
4 40
0 30
2 20
1 10
dtype: int64
Summary
In this tutorial, we've covered the Series.sort_values()
method in Pandas, which allows you to sort the values of a Series in either ascending or descending order, with options for in-place sorting and handling NaN values.