Q&A library Python

How do I find the most common value in a pandas column?

Python Beginner frequencymodevalue-counts

Short answer

Use mode, which returns every value tied for most frequent, or value_counts().idxmax() for a single answer. mode returns a Series precisely because there can be more than one winner.

The short version

mode() returns the most frequent value, or values if several tie, which is why it gives you a Series rather than one item. For a single answer, value_counts().idxmax() picks the first. Being aware of ties is the whole point.

Using mode

import pandas as pd

s = pd.Series([1, 1, 2])

s.mode().tolist()   # [1]

With a tie, it returns both.

pd.Series([1, 1, 2, 2]).mode().tolist()   # [1, 2]

That is not a quirk: with two values appearing equally often, there genuinely is no single most common value, and mode tells you the truth rather than picking one.

Getting one value

If you know or do not care about ties, take the first.

s.mode()[0]                       # the first modal value
s.value_counts().idxmax()         # the label with the highest count

value_counts().idxmax() gives the same answer for the untied case and is a common idiom, but note that it silently picks one winner when there is a tie, exactly the thing mode was warning you about.

Seeing the full picture

Usually you want more than just the winner.

s.value_counts()                   # every value with its count
s.value_counts(normalize=True)     # as proportions

Looking at the top few counts tells you whether the mode is meaningful. A "most common" value that appears in 2 per cent of rows, barely ahead of the next, is not a useful summary, and only the full counts reveal that.

The mode per group

df.groupby("city")["product"].agg(lambda s: s.mode()[0])

This gives each city's most common product. The [0] picks the first modal value, so be aware you are silently resolving ties. If ties matter, return the whole mode and handle it explicitly.

Mode of a numeric column

mode works on numbers, but it is rarely useful for a continuous measurement, where most values are unique and the "most common" is essentially arbitrary. For a continuous variable, the median or a histogram tells you far more about the centre and shape than the mode does.

The mode is genuinely informative for categorical data, and for numeric data that is really a code or a rounded count.

Missing values

mode ignores NaN by default, so a column that is mostly missing can report a mode based on very few rows. Check how many non-missing values there were before trusting it, because a mode computed from three rows out of a thousand is not telling you much.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project