idxmax and idxmin
df["col"].idxmax() returns the index label of the row with the largest value (idxmin for the smallest), so df.loc[df["col"].idxmax()] gives that whole row. For the largest value per group use df.loc[df.groupby("k")["col"].idxmax()].
Syntax
Series.idxmax(skipna=True) | Series.idxmin(skipna=True) | df.idxmax(axis=0)| Part | What it is |
|---|---|
skipna | Ignore NaN (default True) |
axis | DataFrame.idxmax: 0 gives the row label of the max per column, 1 gives the column name of the max per row |
Examples
import pandas as pd
df = pd.DataFrame({"name": ["Ana", "Ben", "Cara"],
"dept": ["Sales", "IT", "Sales"],
"salary": [50000, 62000, 58000]})
df["salary"].idxmax()Result: 1
df.loc[df["salary"].idxmax()]Result: name Ben dept IT salary 62000 Name: 1, dtype: object
df.loc[df.groupby("dept")["salary"].idxmax()]Result: name dept salary 1 Ben IT 62000 2 Cara Sales 58000
The highest paid person in each department.
Common mistakes
- idxmax returns the index label, not the position: after filtering, labels are not 0..n; use loc with the label, not iloc.
- ValueError or NaN when the column is all NaN: idxmax has nothing to pick; drop or fill first.
- With ties, idxmax returns the first occurrence only; use df[df.col == df.col.max()] to get all of them.
Practice idxmax and idxmin
These drills check your answer on live data, free, no account needed.
- Top three earnersReturn the three highest-paid employees with only the `name` and `salary` columns, highest salary first.
Questions
What is the difference between idxmax and argmax?
idxmax returns the index label; argmax returns the integer position. On a default index they are the same number.
How do I get the top row per group with all columns?
df.loc[df.groupby("k")["v"].idxmax()] or df.sort_values("v", ascending=False).drop_duplicates("k").
Related
- sort_valuesHow to sort a pandas DataFrame with sort_values: ascending and descending, several columns with mixed order, NaN first, sort by index and reset the index.
- groupbyHow groupby works in pandas: group by one or more columns, apply sum, mean, count or size, get a flat table with as_index=False, and iterate over groups.
- rankHow to rank in pandas with rank: ascending or descending, tie methods (average, min, dense, first), ranking within groups, percentile ranks, integer output.
- loc vs ilocThe difference between loc and iloc in pandas: loc selects by index label and column name, iloc by integer position. Slices, lists and boolean masks.