Reputation: 369
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?
Upvotes: 10
Views: 13044
Reputation: 2060
The trick is to use idxmin()
instead of min()
like so:
df.loc[df['S'].idxmin()]
Upvotes: 0
Reputation: 8931
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()]
Upvotes: 16
Reputation: 30920
You can use boolean indexing
:
df[df.S==df.S.min()]
or
df[df['S'].eq(df['S'].min())]
Upvotes: 7