Skip to main content
v2026.11,986 entries · CC-BY 4.0

idxmax in pandas: DataFrame and Series Syntax, NaN, Ties and Axis

pandas idxmax returns the index label of the first maximum: syntax, axis, skipna, ties, label vs argmax position and the ValueErrors it raises.

Written and maintained by CASRAI Editorial Board

Published

On this page

In pandas, idxmax() returns the index label of the first occurrence of the maximum value: Series.idxmax() returns a single label, while DataFrame.idxmax() returns a Series holding one label per column (axis=0, the default) or one label per row (axis=1). Missing values are skipped by default, and ties go to the first label. This guide covers the exact syntax from the pandas documentation, a research-style worked example, how idxmax differs from argmax, and the errors it raises.

What idxmax in pandas is used for in research

Analysts use idxmax when the question is which entity holds the largest value, not how large the value is. Typical questions in a research dataset are which treatment group has the highest mean outcome, in which week each participant peaked, or which instrument recorded the strongest signal. The pandas documentation describes DataFrame.idxmax as returning the index of the first occurrence of the maximum over the requested axis, with NA/null values excluded, and describes it as the DataFrame version of ndarray.argmax.

The companion method idxmin() is identical except that it returns the first occurrence of the minimum. Everything below applies to both, so you can swap the name when you need the smallest value.

Series.idxmax and DataFrame.idxmax signatures

The two signatures documented for the current pandas release (3.1.1 at the time these pages were read) are:

  • DataFrame.idxmax(axis=0, skipna=True, numeric_only=False), returning a Series.
  • Series.idxmax(axis=0, skipna=True, *args, **kwargs), returning a single index label. Here axis is unused and exists only for compatibility with DataFrame, and the extra arguments have no effect (they exist for NumPy compatibility).

The three arguments of the DataFrame version are:

  • axis: 0 or 'index' (default) finds the maximum down each column and returns a row label for every column; 1 or 'columns' finds the maximum across each row and returns a column label for every row.
  • skipna: when True (default) NA values are excluded. If the entire DataFrame is NA, or if skipna=False and an NA value is present, a ValueError is raised.
  • numeric_only: when True, only float, int or boolean columns are considered. The default is False.

How to install or access pandas for idxmax

The pandas installation page lists two supported routes. With conda, run conda install -c conda-forge pandas (the page recommends Miniforge as the conda distribution). With pip, run pip install pandas. The page recommends installing into a virtual environment so the packages for one project do not interfere with another. Excel readers are an optional extra installed with pip install "pandas[excel]". Once installed, import the library with import pandas as pd; idxmax is a method on every Series and DataFrame, so no separate import is needed. Data types matter for how maximum values compare, so see pandas dtypes: inspect, convert and choose types if a column is not behaving as numeric.

How to use idxmax step by step

The example below uses a small illustrative dataset (not real participant data) showing peak scores for three participants over three weeks. It was run in pandas 3.1.1 and the outputs shown are the actual results.

  1. Build or load the data.
    import pandas as pd
    import numpy as np
    
    w = pd.DataFrame(
        {"week1": [3.2, 4.8, 4.1],
         "week2": [5.0, 4.1, np.nan],
         "week3": [4.4, 6.3, 3.9]},
        index=["P01", "P02", "P03"],
    )
  2. Find the row label of the maximum in each column.
    w.idxmax()
    # week1    P02
    # week2    P01
    # week3    P02

    This answers “which participant scored highest in each week”. The NaN for P03 in week 2 is skipped.

  3. Find the column label of the maximum in each row.
    w.idxmax(axis=1)
    # P01    week2
    # P02    week3
    # P03    week1

    This answers “in which week did each participant peak”.

  4. Use the label to retrieve the whole record. Because idxmax returns a label rather than a position, it pairs directly with .loc:
    w.loc[w["week3"].idxmax()]
    # week1    4.8
    # week2    4.1
    # week3    6.3
    # Name: P02
  5. Apply it to a grouped result. To find the group with the highest mean, aggregate first, then call idxmax on the resulting Series:
    df = pd.DataFrame({"site": ["A", "A", "B", "B", "C", "C"],
                       "score": [4.1, 5.2, 6.0, 5.8, 3.3, np.nan]})
    m = df.groupby("site")["score"].mean()
    # A    4.65
    # B    5.90
    # C    3.30
    m.idxmax()
    # 'B'

When your rows are identified by several index levels rather than one label, the returned value is a tuple; see MultiIndex in pandas for how to select with such labels. If you only need the rows whose value passes a condition rather than the single maximum, pandas query is the better tool.

The pandas documentation example

The official DataFrame.idxmax page uses a table of food consumption and emissions: df = pd.DataFrame({"consumption": [10.51, 103.11, 55.48], "co2_emissions": [37.2, 19.66, 1712]}, index=["Pork", "Wheat Products", "Beef"]). Calling df.idxmax() returns Wheat Products for consumption and Beef for co2_emissions, and df.idxmax(axis="columns") returns co2_emissions for Pork, consumption for Wheat Products and co2_emissions for Beef.

Series.idxmax, NaN and ties

For a Series, the documentation states that it returns the row label of the maximum value, and that if multiple values equal the maximum, the first row label with that value is returned. The official example is s = pd.Series([1, None, 4, 3, 4], index=list("ABCDE")): s.idxmax() returns 'C'. The None at label B is skipped, and the tie between C and E is resolved in favour of C, the first one.

How to read the output

The shape of the result depends on the object and the axis, which is where most confusion arises.

  • Series.idxmax() returns one scalar: an index label, whatever type the index holds (string, integer, date, tuple).
  • DataFrame.idxmax(axis=0) returns a Series indexed by the DataFrame’s column names; each value is a row label.
  • DataFrame.idxmax(axis=1) returns a Series indexed by the DataFrame’s row labels; each value is a column name.

A useful rule: the result’s index tells you what was scanned, and the result’s values are the answer. In w.idxmax() above, the result is indexed by week (what was scanned) and each value is a participant. The value is a label, not a number, so it will look like data from your index rather than a score. If you also need the maximum value itself, use max() on the same axis, or retrieve it with .loc.

idxmax versus argmax: labels versus positions

The documentation for Series.idxmax says it is the Series version of ndarray.argmax, and that it returns the label while argmax returns the position; to get the position it points to series.values.argmax(). The pandas Series.argmax page confirms that Series.argmax returns an integer position (zero-indexed) and that, like idxmax, it returns the first occurrence on ties and raises a ValueError if every value is NA or if skipna=False meets an NA value. For the NumPy function itself, see NumPy argmax; the NumPy reference documents numpy.argmax(a, axis=None, out=None, *, keepdims), which by default indexes into the flattened array and also returns the first occurrence when the maximum repeats. On the Series from the docs example, s.argmax() gives 2 (the position) while s.idxmax() gives 'C' (the label); both are the same element. Use positions with .iloc and labels with .loc.

Troubleshooting idxmax

The documented failure conditions are few, and each can be reproduced:

ValueError with skipna=False

If skipna=False and the scanned row or column contains a missing value, pandas raises a ValueError. In pandas 3.1.1 running w.idxmax(axis=1, skipna=False) on the data above raised ValueError: Encountered an NA value with skipna=False. Either leave skipna=True or fill/drop missing values first, a choice that should be justified in your analysis plan, since skipping NaN silently changes which entity wins.

ValueError on empty or all-NA data

The documentation states that a ValueError is raised if the row or column is empty (and, for a DataFrame, if the entire DataFrame is NA). Calling pd.Series([], dtype=float).idxmax() in pandas 3.1.1 raised ValueError: attempt to get argmax of an empty sequence. This commonly appears after a filter returns no rows, so check .empty before calling.

Mixed column types

With numeric_only=False (the default), every column is considered. To restrict the scan to float, int or boolean columns, pass numeric_only=True. In pandas 3.1.1, a two-column frame with one numeric and one text column returned a label for both columns by default, and only the numeric column with numeric_only=True, so a text column can silently join the result if you do not set it.

Ties hide information

Because only the first occurrence is returned, two entities tied for the maximum look like one winner. If ties matter, compare against the maximum directly, for example w["week3"] == w["week3"].max(), to list every tied label.

Free alternatives to idxmax

pandas and NumPy are both free, open-source libraries, and the data table below compares the documented behaviour of the methods that solve the same problem. Choose by whether you want a label or a position, and which object you hold.

Method Returns Best used when
Series.idxmax() Index label of the first maximum You have a labelled Series and want the label.
DataFrame.idxmax() Series of labels, one per column or row You want the winner for every column or row at once.
Series.argmax() Integer position of the first maximum You need a zero-based position for .iloc.
numpy.argmax Integer position in an array You are working with plain NumPy arrays.
idxmin() Index label of the first minimum You want the smallest value’s label instead.

Frequently asked questions

What does idxmax do in pandas?

It returns the index label of the first occurrence of the maximum value, excluding NA values by default. On a DataFrame it does so per column or per row depending on axis.

Is pandas idxmax the same as argmax?

No. idxmax returns the label; argmax returns the integer position. They point to the same element, but label and position differ whenever the index is not the default 0, 1, 2 range.

What happens when there is a tie for the maximum?

The first label with that value is returned, as the Series.idxmax documentation states.

How do I get idxmax across rows instead of columns?

Pass axis=1 (or axis='columns') to DataFrame.idxmax.

Sources

Data: pandas label-returning and position-returning maximum methods: documented behaviour

Compares documented behaviour of pandas idxmax, idxmin and argmax methods (return type, NA handling, tie rule, axis support), compiled from the official pandas API reference pages.

pandas label-returning and position-returning maximum methods: documented behaviour
MethodReturnsTie ruleNA handlingAxis argument
DataFrame.idxmaxSeries of index labelsFirst occurrenceExcluded by default; ValueError if skipna=False and NA present or all NAaxis=0 or 1
Series.idxmaxSingle index labelFirst row label with the valueExcluded by default; ValueError if emptyUnused, compatibility only
DataFrame.idxminSeries of index labelsFirst occurrence of minimumExcluded by default; ValueError if skipna=False and NA present or all NAaxis=0 or 1
Series.argmaxInteger positionFirst occurrenceExcluded by default; ValueError if skipna=False and NA present or all NANone (unused)

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about idxmax in pandas: DataFrame and Series Syntax, NaN, Ties and Axis

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →