[Python] 특정 값이 최대값을 가지는 행(row) 추출
업데이트:
개요

아래 데이터프레임을 예제로 보자.
import pandas as pd
...
df.head()
| sepal length (cm) | sepal width (cm) | petal length (cm) | petal width (cm) | target | |
|---|---|---|---|---|---|
| 0 | 5.1 | 3.5 | 1.4 | 0.2 | setosa | 
| 1 | 4.9 | 3.0 | 1.4 | 0.2 | setosa | 
| 2 | 4.7 | 3.2 | 1.3 | 0.2 | setosa | 
| 3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa | 
| 4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa | 
target 컬럼에는 setosa, versicolor, virginica 3개의 범주가 있다.
이 세 범주의 “sepal length (cm)” 최대값을 가지는 행(row)을 추출해보자.
1. idxmax() 이용
df.loc[df.groupby(['target'])['sepal length (cm)'].idxmax()]
| sepal length (cm) | sepal width (cm) | petal length (cm) | petal width (cm) | target | |
|---|---|---|---|---|---|
| 14 | 5.8 | 4.0 | 1.2 | 0.2 | setosa | 
| 50 | 7.0 | 3.2 | 4.7 | 1.4 | versicolor | 
| 131 | 7.9 | 3.8 | 6.4 | 2.0 | virginica | 
2. sort_values(), drop_duplicates() 활용
df.sort_values(by=['target','sepal length (cm)'], ascending=False).drop_duplicates(subset=['target'], keep='first')
| sepal length (cm) | sepal width (cm) | petal length (cm) | petal width (cm) | target | |
|---|---|---|---|---|---|
| 131 | 7.9 | 3.8 | 6.4 | 2.0 | virginica | 
| 50 | 7.0 | 3.2 | 4.7 | 1.4 | versicolor | 
| 14 | 5.8 | 4.0 | 1.2 | 0.2 | setosa | 
 
      
     
       
       
      
댓글남기기