Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- pycharm
- Python
- 퀀트
- line number
- freeze_support
- 우리FIS
- 필기
- 파이썬
- 구현
- highlight.js
- 진행 상황
- 금융결제원
- 하이라이트
- QueueHandler
- Windows
- DataFrame
- idxmax
- CSS
- multiprocessing
- 웹크롤링
- 티스토리
- idxmin
- 멀티 로그인
- 의사 클래스
- Tistory
- 금결원
- OpenAPI+
- 코드블럭
- pywinauto
- HTML
Archives
- Today
- Total
맨땅에 헤딩하는 사람
Python DataFrame 최대 scalar 값의 index, column 구하기 본문
pandas
는 idxmax()
, idxmin()
이란 method를 제공한다. parameter axis
에 따라(column 혹은 row 기준에 따라) 최대값의 index, column Series
를 반환하는 기능을 가진다. 많이 사용하진 않겠지만 DataFrame
의 2차원 데이터 중 가장 큰 스칼라 값 하나의 index와 column이 궁금한 경우가 있다. 이는 간단하게 idxmax()
를 두 번 적용하는 것으로 해결할 수 있다. 아래 예제 코드를 보자.
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.array([[5,2,4],[6,1,5],[7,1,3]]),
... columns=['a', 'b', 'c'])
>>> df
a b c
0 5 2 4
1 6 1 5
2 7 1 3
>>> idx = df.idxmax()
>>> idx
a 2
b 0
c 1
dtype: int64
>>> sr = pd.Series([df.at[idx[i], i] for i in idx.index],
... index=idx.index)
>>> sr
a 7
b 2
c 5
dtype: int64
>>> idx_s = sr.idxmax()
>>> idx_s
'a'
>>> print(f"max : df.at[{idx[idx_s]}, {idx_s}] = {sr[idx_s]}")
max : df.at[2, a] = 7
|
cs |
- 2차원의
DataFrame
에서idxmax()
메소드를 사용하여 각 column마다 가장 큰 값의 index를 얻는다. (변수명idx
) - 이를 바탕으로 각 column마다 최대값을 가지는
Series
를 생성한다. (변수명sr
) - Series에서
idxmax()
메소드를 사용하여 최대 column 값을 얻는다. (변수명idx_s
) - 최대값의 column은
idx_s
이고 index는idx[idx_s]
임을 알 수 있으므로 값까지 추출해낼 수 있다.df.at[idx[idx_s], idx]
혹은sr[idx_s]
최소값의 column과 index를 구하는 방법 역시 idxmin()
을 사용하여 동일하게 구하면 된다.
'파이썬 > 이론' 카테고리의 다른 글
Python multiprocessing에서 logging 사용하기 (QueueHandler) (0) | 2020.08.30 |
---|---|
[Python] pandas DataFrame 최적화 (삽입, 생성, 반복, 문자열) (0) | 2020.08.25 |
[Python] tqdm을 사용하여 for 반복, 함수 진행률 출력하기 (0) | 2020.08.23 |
[Python] Windows GUI 자동화 pywinauto 사용법 (4) | 2020.08.22 |
Windows 환경 python multiprocessing 시 freeze_support() (0) | 2020.08.09 |
Comments