data analysis
pandas
maximum value
python programming
data frame

Find the column name which has the maximum value for each row

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In pandas, the shortest way to get the column label containing the maximum value in each row is idxmax(axis=1). It is fast, expressive, and usually much better than writing a Python loop over rows.

Use idxmax Across Columns

Suppose you have scores from several models and you want to know which model won for each row:

python
1import pandas as pd
2
3df = pd.DataFrame(
4    {
5        "model_a": [0.81, 0.72, 0.65],
6        "model_b": [0.78, 0.74, 0.91],
7        "model_c": [0.80, 0.71, 0.88],
8    }
9)
10
11winner = df.idxmax(axis=1)
12
13print(winner)

Output:

text
10    model_a
21    model_b
32    model_b
4dtype: object

axis=1 tells pandas to operate across columns for each row. The result is a Series containing the column label of the maximum value.

Add the Result Back to the DataFrame

Often you want to keep the winning column name as a new field:

python
df["best_model"] = df.idxmax(axis=1)
print(df)

That is useful for reports, downstream filtering, or audit output.

If you also want the corresponding maximum value, combine idxmax with max:

python
df["best_model"] = df.idxmax(axis=1)
df["best_score"] = df.max(axis=1)

Now each row tells you both what won and by how much.

Restrict the Search to Specific Columns

Sometimes the DataFrame contains metadata columns that should not participate in the comparison. In that case, select only the numeric or relevant columns first:

python
1score_cols = ["model_a", "model_b", "model_c"]
2
3df["best_model"] = df[score_cols].idxmax(axis=1)
4df["best_score"] = df[score_cols].max(axis=1)

This is the right pattern when your DataFrame also contains IDs, timestamps, or categorical fields.

How Ties Work

idxmax returns the first column label with the maximum value. That is important if ties are possible.

python
1df = pd.DataFrame(
2    {
3        "a": [5],
4        "b": [5],
5        "c": [3],
6    }
7)
8
9print(df.idxmax(axis=1))

The result is a, not both a and b.

If you need all tied columns, you need a different approach:

python
row_max = df.max(axis=1)
tied = df.eq(row_max, axis=0)
print(tied)

That returns a boolean mask showing every column whose value matches the row maximum.

Missing Values and Data Types

idxmax ignores missing values by default, but mixed dtypes can still cause confusion. If the DataFrame contains strings or objects mixed with numbers, make sure you compare only the intended columns.

For example:

python
numeric = df.select_dtypes(include="number")
best_numeric_col = numeric.idxmax(axis=1)

This prevents pandas from trying to compare incompatible values or from using columns that were never supposed to be part of the maximum search.

Why a Vectorized Solution Is Better

A row loop with iterrows() works on tiny data, but it is slower and noisier:

python
results = []
for _, row in df.iterrows():
    results.append(row.idxmax())

The vectorized version is both shorter and more idiomatic:

python
results = df.idxmax(axis=1)

That is one of the main advantages of pandas: operations over whole axes are clearer and usually faster than manual loops.

Common Pitfalls

  • Forgetting axis=1, which makes pandas search down each column instead of across each row.
  • Including non-comparable columns in the DataFrame slice.
  • Assuming idxmax returns all ties when it only returns the first maximum.
  • Using iterrows() for a task pandas already solves with one vectorized call.
  • Forgetting to keep the selected comparison columns consistent when the DataFrame schema changes.

Summary

  • Use df.idxmax(axis=1) to get the column name of the maximum value for each row.
  • Add the result back to the DataFrame when you want an explicit winner column.
  • Slice to relevant columns first if the DataFrame contains metadata or mixed types.
  • 'idxmax returns the first maximum when ties occur.'
  • This vectorized approach is usually cleaner and faster than looping over rows manually.

Course illustration
Course illustration

All Rights Reserved.