Knowledge base / Python

pandas idxmax: maximum labels, ties and missing values

I separate the maximum’s label, value and position on small data and show how to handle an absence of valid candidates.

Kajo RudzińskiPublished Updated 4 min read

A selector pointing at the first of two equally tall towers and its blank label.

I choose idxmax() when I need the label where a maximum occurs. The maximum value is a different answer, as is a zero-based position. Those answers can look similar with a simple numeric index, so I begin with text labels and a tie. The examples are synthetic and target pandas 3.1.1. Older tutorials need care because pandas 3.0 changed handling of some missing-value cases.

A Series returns the first maximum’s label

The Series.idxmax documentation specifies the label of the first maximum. Consider values 8, 15 and 15 with labels a, b and c:

import pandas as pd

scores = pd.Series([8, 15, 15], index=["a", "b", "c"])
winner = scores.idxmax()

Here, winner is "b". The maximum value is 15 and its first zero-based position is 1. Label, value and position are different information. Use Series.argmax for the position and scores.max() for the value. A variable name should show which answer it holds, particularly when the index also contains numbers.

Data order settles the tie. Moving c before b makes another label first without changing their scores. I would not mistake that for a business rule selecting a better product or team. If the task requires every leader, one label is insufficient. Decide whether to preserve the tie or resolve it with another explicit criterion, such as a date.

Select every tied maximum when needed

To retain ties, compare values with the maximum and select matching elements. The loc documentation describes selection with a boolean mask.

leaders = scores.loc[scores.eq(scores.max())]

For our data, leaders contains b with 15 and c with 15. It is a Series of selected observations rather than one index label. You can report that the maximum is shared instead of discarding a valid leader merely to fit a dashboard card. The shape of the answer should follow the question.

A nonunique index creates another issue: the label from idxmax may not identify one row. Selecting that label with loc can return several records. Establish the index meaning and a stable observation identifier. Resetting the index changes labels, so a previously saved result may lose its meaning. Keep the answer connected to the dataset on which it was calculated.

A DataFrame returns a Series along the chosen axis

With a DataFrame, axis=0 gives a row label for each column’s maximum. axis=1 gives a column label for each row’s maximum. The output is a Series, as documented by DataFrame.idxmax.

frame = pd.DataFrame(
    {"A": [8, 15, 15], "B": [20, 3, 4]},
    index=["a", "b", "c"],
)

by_column = frame.idxmax()
by_row = frame.idxmax(axis=1)

by_column maps A to b and B to a. by_row maps a to B and both b and c to A. This is not a one-row table with columns A and B. I also avoid copying an old printed dtype line as a guarantee of representation formatting. The important information here is the values and the kind of object returned for further work.

For axis=1, compare measures with compatible meanings. The largest number among age, salary and order count does not identify a useful best feature. A and B here are scores on the same arbitrary scale. In a real report, choose comparable columns first. numeric_only=True can restrict included types to numeric and boolean data, but it cannot establish compatible units.

A magnifying lens examining an empty slot among existing data pillars.

Make missing-value handling explicit in pandas 3

The default skipna=True excludes missing observations if values remain to compare. In this Series, the largest known value has label c:

partial = pd.Series([8, None, 15], index=["a", "b", "c"])
known_winner = partial.idxmax()

That does not establish that c also beats the unknown observation. State that you are selecting a maximum among available values. This is an interpretation choice rather than merely a parameter. If a missing observation indicates a measurement failure, investigating the source may be preferable to selecting a winner at any cost.

In pandas 3.1.1, partial.idxmax(skipna=False) raises ValueError because a missing value is present. An all-missing Series has no valid maximum, and an empty Series also raises an error. The pandas 3.0 release notes describe the change from earlier missing-result behavior. Do not present skipna=False as a way to obtain NaN. For a DataFrame, also check for all-missing data along the direction being analyzed.

Handle the absence of valid candidates

If the task permits selecting among known observations, remove missing values from one Series and check whether anything remains. Series.dropna preserves remaining labels by default:

valid = partial.dropna()
if valid.empty:
    winner = None
else:
    winner = valid.idxmax()

For partial, a and c remain and c wins. With no known observations, this example assigns the sentinel None. That is a choice in the surrounding code, rather than a value returned by idxmax. If None could itself be a valid index label, represent result availability separately so an absent candidate cannot be confused with a real label.

As an exercise, change scores’ last value to 18 and identify the maximum’s label, value and position separately. Then consider reordering records and whether the task needs all ties. For related identifier issues, read about pandas duplicated. Define the observation before choosing how to identify its maximum.

Key takeaways

Does idxmax return the largest value?

No. It returns the label; max returns the value and argmax gives a zero-based position.

What happens with tied maxima?

idxmax selects the first occurrence in data order. Use a separate selection, such as a mask, to preserve all ties.

Does skipna=False return NaN?

In pandas 3.1.1, a missing value with skipna=False raises ValueError. An all-missing Series also has no valid maximum.

AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.

Kajo Rudziński

Newsletter KajoData

Let’s keep in touch.

I write about data analysis, learning and changing careers. My newsletter and the sign-up form are in Polish. If that works for you, I’d be glad to see you there.