Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to sort a Pandas Series?
Sorting a Pandas Series is a common data manipulation task. The sort_values() method provides flexible options for arranging data in ascending or descending order while preserving the original index associations.
Basic Sorting with sort_values()
The sort_values() method sorts a Series by its values and returns a new sorted Series ?
import pandas as pd
# Create an unsorted Series
numbers = pd.Series([18, 15, 66, 92, 55, 989])
print("Unsorted Pandas Series:")
print(numbers)
# Sort in ascending order (default)
sorted_asc = numbers.sort_values()
print("\nSorted in Ascending Order:")
print(sorted_asc)
Unsorted Pandas Series: 0 18 1 15 2 66 3 92 4 55 5 989 dtype: int64 Sorted in Ascending Order: 1 15 0 18 4 55 2 66 3 92 5 989 dtype: int64
Sorting in Descending Order
Use the ascending=False parameter to sort in descending order ?
import pandas as pd
numbers = pd.Series([18, 15, 66, 92, 55, 989])
# Sort in descending order
sorted_desc = numbers.sort_values(ascending=False)
print("Sorted in Descending Order:")
print(sorted_desc)
Sorted in Descending Order: 5 989 3 92 2 66 4 55 0 18 1 15 dtype: int64
Sorting with String Values
The sort_values() method also works with string data, sorting alphabetically ?
import pandas as pd
fruits = pd.Series(['banana', 'apple', 'cherry', 'date'])
print("Original Series:")
print(fruits)
sorted_fruits = fruits.sort_values()
print("\nSorted Alphabetically:")
print(sorted_fruits)
Original Series: 0 banana 1 apple 2 cherry 3 date dtype: object Sorted Alphabetically: 1 apple 0 banana 2 cherry 3 date dtype: object
In-Place Sorting
Use inplace=True to modify the original Series instead of creating a new one ?
import pandas as pd
numbers = pd.Series([18, 15, 66, 92, 55])
print("Before in-place sorting:")
print(numbers)
# Sort in-place
numbers.sort_values(inplace=True)
print("\nAfter in-place sorting:")
print(numbers)
Before in-place sorting: 0 18 1 15 2 66 3 92 4 55 dtype: int64 After in-place sorting: 1 15 0 18 4 55 2 66 3 92 dtype: int64
Key Parameters
| Parameter | Default | Description |
|---|---|---|
ascending |
True | Sort in ascending (True) or descending (False) order |
inplace |
False | Modify original Series (True) or return new Series (False) |
na_position |
'last' | Position NaN values: 'first' or 'last' |
Conclusion
Use sort_values() to sort Pandas Series by values. The method preserves original indices and offers flexible options for ascending/descending order and in-place modification.
Advertisements
