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 pd
data = {'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 Age
0 Ben 36
1 Anna 27
2 Zoe 20
3 Tom 12
4 John 30
5 Steve 20
6 Becky 22
7 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 Tom
Age 12
Name: 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 pd
data = {'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 Age
0 Ben 12
1 Anna 27
2 Zoe 20
3 Tom 12
4 John 30
5 Steve 20
6 Becky 22
7 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 Age
0 Ben 12
3 Tom 12
and to get the indexes:
df[ df['Age'] == df['Age'].min() ].index
which returns
Int64Index([0, 3], dtype='int64')