Source From Here
Question
Examples of how to find a minimum value in a pandas dataframe column.
HowTo
Create a dataframe
Lets create for example a simple data frame:
Output:
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:
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:
Then using the index above:
Output:
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:
Output:
Then the function min:
however idxmin:
To get rows with a min value in the column Age a solution is to do:
Output:
and to get the indexes:
which return:
Examples of how to find a minimum value in a pandas dataframe column.
HowTo
Create a dataframe
Lets create for example a simple data frame:
- 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
- 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
To find the minimum value in the column Age, a solution is to use the pandas function min:
- df['Age'].min() # Output: 12
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() # Output: 3
- df.iloc[3,:]
- Name Tom
- Age 12
- Name: 3, dtype: object
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)
- 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
- df['Age'].min() # Output: 12
- df['Age'].idxmin() # Output: 0
- df[ df['Age'] == df['Age'].min() ]
- Name Age
- 0 Ben 12
- 3 Tom 12
- df[ df['Age'] == df['Age'].min() ].index
- Int64Index([0, 3], dtype='int64')
沒有留言:
張貼留言