Examples of how to find a minimum value in a pandas dataframe column:
Create a dataframe
Lets create for example a simple dataframe:
import pandas as pddata = {'Name':['Ben','Anna','Zoe','Tom','John','Steve','Becky','Bob'],'Age':[36,27,20,12,30,20,22,21]}df = pd.DataFrame(data)df
which returns
Name Age0 Ben 361 Anna 272 Zoe 203 Tom 124 John 305 Steve 206 Becky 227 Bob 21
Find the min value in the column Age
To find the minimum value in the column Age, a solution is to use the pandas function min:
df['Age'].min()
that gives the min value:
12
Find the index corresponding to the min value in the column Age
It is also possible to find the index corresponding to the min value in the column Age using the pandas function called idxmin
df['Age'].idxmin()
returns here
3
Then using the index above:
df.iloc[3,:]
we get
Name TomAge 12Name: 3, dtype: object
An example with multiple rows with a min value in the same column
Lets create a dataframe with two min values in the column Age:
import pandas as pddata = {'Name':['Ben','Anna','Zoe','Tom','John','Steve','Becky','Bob'],'Age':[12,27,20,12,30,20,22,21]}df = pd.DataFrame(data)print(df)
gives
Name Age0 Ben 121 Anna 272 Zoe 203 Tom 124 John 305 Steve 206 Becky 227 Bob 21
Then the function min:
df['Age'].min()
returns the min value which is
12
however idxmin
df['Age'].idxmin()
returns only the first index:
0
To get rows with a min value in the column Age a solution is to do:
df[ df['Age'] == df['Age'].min() ]Name Age0 Ben 123 Tom 12
and to get the indexes:
df[ df['Age'] == df['Age'].min() ].index
which returns
Int64Index([0, 3], dtype='int64')
