2021年1月25日 星期一

[ 常見問題 ] How to find a minimum/maximum value in a pandas dataframe column ?

 Source From Here

Preface
Below will provide examples of how to find a minimum value in a pandas Dataframe's column:

HowTo

Create a dataframe
Lets create for example a simple dataframe:
test.py
  1. import pandas as pd  
  2.   
  3. data = {'Name':['Ben','Anna','Zoe','Tom','John','Steve','Becky','Bob'],  
  4.         'Age':[36,27,20,12,30,20,22,21]}  
  5.   
  6. df = pd.DataFrame(data)  
  7. print(f"{df}")  
which returns:
  1.     Name  Age  
  2. 0    Ben   36  
  3. 1   Anna   27  
  4. 2    Zoe   20  
  5. 3    Tom   12  
  6. 4   John   30  
  7. 5  Steve   20  
  8. 6  Becky   22  
  9. 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:
>>> from test import *
>>> df['Age'].min()
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()
3

Then using the index above:
>>> df.iloc[df['Age'].idxmin(), :]
  1. Name    Tom  
  2. Age      12  
  3. 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:
>>> from test import *
  1.     Name  Age  
  2. 0    Ben   12  
  3. 1   Anna   27  
  4. 2    Zoe   20  
  5. 3    Tom   12  
  6. 4   John   30  
  7. 5  Steve   20  
  8. 6  Becky   22  
  9. 7    Bob   21  

Then the function min:
>>> df['Age'].min()
12

However, the idxmin will only return only the first one with minimum value:
>>> df['Age'].idxmin()
0

To get all row(s) with a min value in the column Age, a solution is to do:
>>> df[df['Age'] == df['Age'].min()]
  1.   Name  Age  
  2. 0  Ben   12  
  3. 3  Tom   12  

and to get the indexes:
>>> df[df['Age'] == df['Age'].min()].index
Int64Index([0, 3], dtype='int64')

>>> list(df[df['Age'] == df['Age'].min()].index)
[0, 3]


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...