sort_values() (Pandas)
df.sort_values() reorders the rows of a DataFrame or the elements of a Series by the values in one or more columns. It is how you rank, order, and find the largest or smallest records.
Pandas
Pass a column name (or a list of names) to by and pandas sorts ascending by default. Set ascending=False for descending, or pass a list of booleans to sort each key in a different direction — sort by team ascending then score descending, for instance.
By default missing values sort to the end regardless of direction; na_position='first' moves them up front. The sort is not stable unless you choose kind='mergesort', which matters when ties must keep their original order.
sort_values orders by the data; its sibling sort_index orders by the row or column labels instead. For just the top or bottom N rows, nlargest/nsmallest are faster than sorting the whole frame.
Syntax
df.sort_values(by, ascending=True, na_position='last')Examples
Python
import pandas as pd
s = pd.Series([3, 1, 2])
print(s.sort_values())Output:
1 1
2 2
0 3
dtype: int64Learn it in a lesson
- Sorting →