Coding Ref

How to sort a series in Pandas

How to sort a series in Pandas

To sort a Pandas series, you can use the sort_values() method. This method allows you to sort the data in the series by the values in the series, either in ascending or descending order.

Here's an example of using the sort_values() method to sort a Pandas series:

main.py
import pandas as pd

# create a sample series
s = pd.Series([3, 2, 1, 4, 5])

# sort the series in ascending order
s_sorted = s.sort_values()

# display the result
print(s_sorted)

This will sort the data in the series in ascending order, based on the values in the series.

The output will be:

output
2    1
1    2
0    3
3    4
4    5
dtype: int64

Specify the sorting order

You can also use the sort_values() method to specify the sorting order.

For example:

main.py
# sort the series in descending order
s_sorted = s.sort_values(ascending=False)

# display the result
print(s_sorted)

This will sort the data in the series in descending order, based on the values in the series.

The output will be:

output
4    5
3    4
0    3
1    2
2    1
dtype: int64

Conclusion

The sort_values() method is a convenient way to sort the data in a Pandas series by the values in the series. You can specify the sorting order (ascending or descending) to control the order of the data in the sorted series.

You'll also like

Related tutorials curated for you

    How to find the minimum in Pandas

    What is nlargest() in Pandas?

    How to drop duplicate columns in Pandas

    How to calculate the variance in Pandas DataFrame

    How to join two DataFrames in Pandas

    How to concatenate in Pandas

    How to make a crosstab in Pandas

    How to use ffill() in Pandas

    How to use intertuples() in Pandas

    How to GroupBy Index in Pandas

    How to use qcut() in Pandas

    How to use applymap() in Pandas