10

I'm trying to select a row in Pandas DatFrame where a column has the lowest value. There should have an easy way of doing that, but so far I didn't find.

Suppose this dataframe:

>>> print(df.head())
    N   M  S
0  10  42  4
1  39  22  2
2  11  52  4
3  97  42  2
4  66  72  1

How do I get the row where a column has the minimum value? For example, how do I get the row where column 'S' has value 1?

2
  • 2
    df[df.S==df.S.min()]
    – ansev
    Commented Nov 3, 2019 at 17:57
  • That's very simple and elegant, thanks @ansev ! Do you min to write that as a solution so I can accept it?
    – Heitor
    Commented Nov 3, 2019 at 20:56

3 Answers 3

15

A column name of df.S works but a column name of df.T doesn't work. df.T invokes the Transpose operation because it takes namespace precedence. Here's @ansev answer using literals instead.

df[df['S']==df['S'].min()]
7

You can use boolean indexing:

df[df.S==df.S.min()]

or

df[df['S'].eq(df['S'].min())]
1
  • That also works to get the row for the max value! In my case I had to add a .drop_duplicates() after that, there were more than one row with the same S value.
    – Heitor
    Commented Nov 4, 2019 at 14:18
1
print(df.loc[df['S']==df['S'].min(),:])
2
  • Thanks, @giulio! Your solution is equivalent to @ansev 's, but a bit more verbose.
    – Heitor
    Commented Nov 4, 2019 at 14:20
  • @heitor It's python philosophy: explicit is better than implicit :) welcome
    – giulio
    Commented Nov 4, 2019 at 19:07

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.