Sub topic 2
Controlling Order and Finding Unique Values in pandas
Assume you know basic Python, can create a pandas DataFrame, and can select a column. These operations return a Series unless noted otherwise.
Controlling the order of the result
value_counts() sorts counts from largest to smallest by default. Use ascending=True for the reverse order. Use sort_index() when you want to order by the values themselves.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo"]
})
by_frequency = df["city"].value_counts()
least_first = df["city"].value_counts(ascending=True)
alphabetical = df["city"].value_counts().sort_index()
print(by_frequency)
print(least_first)
print(alphabetical)ascending controls the count order. sort_index() controls the label order. Do not confuse the two.
| Goal | Expression |
|---|---|
| Most frequent first | `s.value_counts()` |
| Least frequent first | `s.value_counts(ascending=True)` |
| Sort labels | `s.value_counts().sort_index()` |
Listing distinct values with `unique`
unique() returns each distinct value in order of first appearance. It returns a NumPy array, not a Series. Missing values appear in the result when present.
cities = df["city"].unique()
print(cities)Counting distinct values with `nunique`
nunique() returns one integer. It ignores missing values by default. Pass dropna=False to count a missing value as one distinct item.
n_cities = df["city"].nunique()
n_including_missing = df["city"].nunique(dropna=False)Finding duplicate rows with `duplicated`
duplicated() returns a Boolean Series. The first occurrence is False; later rows with the same selected values are True. Use subset to define which columns identify a duplicate.
df["is_duplicate_city"] = df.duplicated(subset=["city"])
print(df)Exercise
Which expression sorts a value_counts result alphabetically by its values?
Show answer
df["city"].value_counts().sort_index()