简体   繁体   中英

Select a pandas dataframe row where column has minimum value

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?

You can use boolean indexing :

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

or

df[df['S'].eq(df['S'].min())]

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()]
print(df.loc[df['S']==df['S'].min(),:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM