Sub topic 1
Sorting rows with sort_values
Prerequisites
This chapter assumes you can:
- Write basic Python, including function calls with keyword arguments.
- Create a pandas DataFrame and select columns with
df["name"]. - Tell a Series (one column) from a DataFrame (a table of columns).
You need pandas installed (pip install pandas). The examples use the small sales table below throughout this chapter and the rest of the tutorial.
What sort_values does
sort_values reorders the rows of a DataFrame according to the values in one or more columns. It returns a new DataFrame. The original is unchanged unless you ask otherwise.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "South", "North", "East", "South", "East"],
"product": ["A", "B", "B", "A", "A", "B"],
"units": [10, 5, None, 8, 12, 7],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 4.0],
})
print(df.sort_values("units", ascending=False))The rows now appear in the order of index labels 4, 0, 3, 5, 1, 2. That is units 12, 10, 8, 7, 5, and finally the missing value.
Three details matter here.
- The index labels travel with their rows. Row 4 is still labelled 4 after the sort, so
.loc[4]finds the same row before and after. unitshas a missing value, so pandas stores the column as floats (12.0, not12). The sort works on those floats.- The missing value (
NaN) went last even though the sort was descending. That is the default placement. A later section shows how to change it.
The signature
The arguments you will use most often are these.
| Argument | Default | Meaning |
|---|---|---|
| `by` | required for a DataFrame | Column name, or list of names, to sort on |
| `ascending` | `True` | `False` for largest first. A list sets the direction per column |
| `na_position` | `"last"` | `"first"` puts missing values at the top |
| `inplace` | `False` | Modify the DataFrame instead of returning a new one |
| `ignore_index` | `False` | Renumber the result 0, 1, 2, ... |
| `key` | `None` | Function applied to the values before comparing |
| `kind` | `"quicksort"` | Algorithm used when sorting a single column |
| `axis` | `0` | `0` sorts rows. `1` sorts columns by the values in given rows |
Later chapters cover multiple columns, key, ignore_index and stability in detail. This chapter covers the single-column case and the behaviour every sort shares.
Sorting does not change the original
A common mistake is to call sort_values and expect df to change.
df.sort_values("units")
print(df.index.tolist()) # still [0, 1, 2, 3, 4, 5]
df = df.sort_values("units")
print(df.index.tolist()) # [1, 5, 3, 0, 4, 2]The first call builds a sorted copy and throws it away. To keep the result, assign it to a name. This chapter's later examples assume you rebuild df from the first listing, since the second call above replaced it.
inplace=True exists, but it does not save memory in most cases and it prevents method chaining. Assigning the result is the usual style.
Sorting a Series
A Series has no by argument, because it has only one column of values.
s = pd.Series([3, 1, 2], index=["x", "y", "z"])
print(s.sort_values(ascending=False))The result is x (3), z (2), y (1). When you select one column from a DataFrame, you get a Series, so df["units"].sort_values() returns just that column ordered. The row labels still tell you which original rows the values came from.
Missing values
By default, pandas places NaN at the end, in both ascending and descending sorts. This is different from SQL databases, where the default placement depends on the system and the direction.
print(df.sort_values("units", na_position="first"))For the original table, this gives the index order 2, 1, 5, 3, 0, 4. The missing row comes first, then units 5, 7, 8, 10, 12.
Missing values are never compared with real values. They are set aside and placed at one end. That is why ascending does not move them.
How different data types sort
The sort order depends on the column's data type (dtype), not on how the values look when printed.
- Numbers sort numerically.
- Strings sort by character code, one character at a time. Uppercase letters come before lowercase letters.
- Dates sort chronologically if the column has a datetime dtype. Dates stored as text sort as plain strings.
Two examples show how this causes surprises.
words = pd.Series(["banana", "Cherry", "apple"])
print(words.sort_values())The result is Cherry, apple, banana, because "C" sorts before "a". The key argument, covered later, fixes this.
codes = pd.Series(["10", "9", "100"])
print(codes.sort_values().tolist())
print(pd.to_numeric(codes).sort_values().tolist())The first line prints ['10', '100', '9'], which is text order. The second prints [9, 10, 100], which is the order you probably wanted. If a column of numbers sorts strangely, check df.dtypes and convert with pd.to_numeric before sorting.
Sorting and then slicing
Sorting is often the first step in a two-step pattern: order the rows, then take the first few.
top_two = df.sort_values("units", ascending=False).head(2)
print(top_two)This returns the rows with 12 and 10 units. It works, but it sorts the whole table to get two rows. A later chapter introduces nlargest and nsmallest, which express this intent directly and skip the full sort.
Common errors
KeyError: 'Units': the name inbymust match the column name exactly, including case. Checkdf.columns.TypeErrorabout<not supported: the column mixes types, such as numbers and strings. Convert it to one type first.ValueError: Length of ascending (2) != length of by (1): you passed a list forascendingthat is longer or shorter than the list of columns. With one column, pass a singleTrueorFalse.TypeError: missing required argument 'by': callingdf.sort_values()on a DataFrame with no column name. A Series does not need one. A DataFrame does.- Result seems unsorted: you probably forgot to assign it, as shown above.
Choosing between options
- Use
ascending=Falsewhen you want the largest values at the top, for example for a leaderboard. - Use
na_position="first"when missing data is itself what you want to inspect. - Use
ignore_index=Truewhen the old labels no longer matter, such as before writing a report or exporting to CSV. - Avoid
inplace=Trueunless you have a reason. It makes code harder to chain and to test.
Exercise
Starting from the sales DataFrame in this chapter, write one line that returns the rows ordered by price from highest to lowest, with the original row labels kept. Then say what happens to the row with a missing units value if you instead sort by units descending.
Show answer
df.sort_values("price", ascending=False) returns the rows ordered by price with their original index labels. The three rows priced 4.0 come before the three priced 2.5. Sorting by units with ascending=False still puts the row with the missing value (label 2) last, because na_position defaults to "last" regardless of direction.
Exercise
A column order_id holds the text values "7", "12" and "100". df.sort_values("order_id") returns them as "100", "12", "7". Why, and how do you get numeric order?
Show answer
The column has a string dtype, so pandas compares the characters one by one, and "1" sorts before "7". Convert the column first, for example df["order_id"] = pd.to_numeric(df["order_id"]), then sort. The order is then 7, 12, 100.