6

I'd like to get the index and column name of the minimum value in a pandas DataFrame across all rows and all columns.

I've tried .idxmin but this seems to only work when applied on a column. Ideally the function is a one-liner that doesn't require loops. It seems like a very common problem, but I haven't found a solution yet.

My DataFrame:

      col0, col1, col2
index0 1     2     3 
index1 2     3     4
index2 5     6     7

I'd like to get the index and column for the minimum value across matrix: 1.

so:

some_func(df) = (index0,col0)
2
  • df.idxmin(1) ? Commented Sep 6, 2019 at 17:19
  • You can get the min value of the whole dataframe with df.min().min() may be someone else can tell us how to get the index & column for that value. Commented Sep 6, 2019 at 17:26

2 Answers 2

12

Try this:

df.stack().idxmin()

Out[108]: ('index0', 'col0')
Sign up to request clarification or add additional context in comments.

Comments

2

Numpy and divmod

i, j = divmod(np.argmin(np.ravel(df)), df.shape[1])

(df.index[i], df.columns[j])

('index0', 'col0')

2 Comments

I always like your numpy solution :) +1
Your's is super slick though (-:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.