@MZeeshanM to PythonEnglish • 4 days ago

How do you count the frequency of unique values in a Pandas DataFrame column?

message-square
0
1
How do you count the frequency of unique values in a Pandas DataFrame column?
@MZeeshanM to PythonEnglish • 4 days ago

Call df["col"].value_counts(dropna=False) on the target Series to return a descending-sorted Series mapping each unique value to its occurrence count, passing normalize=True when you want relative proportions (0.0–1.0) instead of raw counts or .reset_index(name="count") to convert the result into a clean two-column DataFrame.

Basic Example

import pandas as pd

df = pd.DataFrame({
    "status": ["paid", "pending", "paid", "failed", "paid", None],
    "amount": [100, 50, 200, 75, 150, 40],
})

# 1. Recommended: Frequency counts including missing values (NaN / None)
counts = df["status"].value_counts(dropna=False)
print(counts)
# Output:
# status
# paid       3
# pending    1
# failed     1
# NaN        1
# Name: count, dtype: int64

# 2. Relative proportions / percentages (sums to 1.0):
pct = (df["status"].value_counts(normalize=True, dropna=False) * 100).round(1)
print(pct)
# Output:
# status
# paid       50.0
# pending    16.7
# failed     16.7
# NaN        16.7
# Name: proportion, dtype: float64

# 3. Convert directly into a tidy DataFrame with explicit column names:
freq_df = df["status"].value_counts(dropna=False).reset_index()
print(freq_df)
#     status  count
# 0     paid      3
# 1  pending      1
# 2   failed      1
# 3      NaN      1

Key Details & Edge Cases

  • value_counts() excludes NaN / None / NaT by default (dropna=True):
    • By default, df["col"].value_counts() silently drops missing values, which can hide data-quality gaps or skew normalize=True percentages over non-null rows only. Always pass dropna=False whenever missing values matter.
  • Preserving original appearance order or sorting alphabetically by value:
    • By default (sort=True, ascending=False), value_counts() sorts from most frequent to least frequent. Pass sort=False to keep the order of first appearance, or chain .sort_index() (df["col"].value_counts().sort_index()) to sort alphabetically/numerically by the unique values themselves.
  • Zero-count categories on Categorical columns (observed=False):
    • If df["col"] has a pd.Categorical dtype with unused categories (e.g., categories ["low", "medium", "high"] where "high" appears 0 times), value_counts() automatically includes "high": 0 in the output (observed=False by default on Series.value_counts()).
  • Binning continuous numeric columns on the fly (bins=n):
    • For continuous numeric columns (such as ages or prices), pass bins=5 (df["amount"].value_counts(bins=5, sort=False)) to bucket values into 5 equal-width intervals and count frequencies per bin without calling pd.cut() separately.
  • Counting multi-column combinations (df.value_counts(["col_a", "col_b"])):
    • Calling .value_counts() directly on the DataFrame (df.value_counts(["region", "status"], dropna=False)) counts joint unique row combinations across multiple columns cleanly without needing .groupby(...).size().

Comparison of Frequency-Counting Methods in Pandas

Method Includes NaN by Default? Default Sort Order Return Type Best Used When
df["col"].value_counts(dropna=False) (Recommended) No (True by default; pass dropna=False) Descending by frequency (sort=True) pd.Series (index = unique values) Counting unique values, percentages (normalize=True), or binned numeric ranges (bins=).
df["col"].value_counts(dropna=False).reset_index() No (pass dropna=False) Descending by frequency pd.DataFrame (["col", "count"]) Exporting frequency tables to CSV/JSON, plotting with Seaborn/Plotly, or merging downstream.
df.value_counts(["col1", "col2"], dropna=False) No (pass dropna=False) Descending by frequency pd.Series with MultiIndex Counting joint occurrences across two or more columns simultaneously.
df.groupby("col", dropna=False).size() No (pass dropna=False) Ascending by group key (sort=True) pd.Series (index = group keys) Combining frequency counts with additional group aggregations via .groupby(...).agg(...).