728x90
728x90
loc, iloc 차이점 비교 (Pandas)
들어가며
- 판다스(Pandas)의
loc
과iloc
함수의 차이점을 정리해본다. - 두 함수는 판다스의 데이터프레임(DataFrame) 객체에서 사용할 수 있다.

loc 함수
개념
- 라벨 기반(Label-based) 인덱싱 방식
- 행과 열의 이름 또는 라벨을 기준으로 데이터를 선택한다.
- 슬라이싱을 할 때, 끝값도 포함된다. (
[a, b]
)
사용 예시 코드
import pandas as pd data = { 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] } df = pd.DataFrame(data, index=['row1', 'row2', 'row3']) """ 출력 결과 A B C row1 1 4 7 row2 2 5 8 row3 3 6 9 """ # 특정 라벨의 행 선택 print(df.loc['row1']) # row1의 데이터 반환 """ 출력 결과 A 1 B 4 C 7 Name: row1, dtype: int64 """ # 특정 라벨의 행과 열 선택 print(df.loc['row1', 'A']) # row1 행의 A 열 데이터 반환 """ 출력 결과 1 """ # 슬라이싱 (라벨 기반) print(df.loc['row1':'row2']) # row1부터 row2까지 포함 """ 출력 결과 A B C row1 1 4 7 row2 2 5 8 """
iloc 함수
개념
- 정수 기반(Integer-based) 인덱싱 방식
- 행과 열의 정수 인덱스 위치를 기준으로 데이터 선택
- 슬라이싱을 할 때 끝값은 포함되지 않는다. (
[a, b)
)
사용 예시 코드
import pandas as pd data = { 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] } df = pd.DataFrame(data, index=['row1', 'row2', 'row3']) """ 출력 결과 A B C row1 1 4 7 row2 2 5 8 row3 3 6 9 """ # 특정 정수 위치의 행 선택 print(df.iloc[0]) # 첫 번째 행 반환 """ 출력 결과 A 1 B 4 C 7 Name: row1, dtype: int64 """ # 특정 정수 위치의 행과 열 선택 print(df.iloc[0, 0]) # 첫 번째 행의 첫 번째 열 데이터 반환 """ 출력 결과 1 """ # 슬라이싱 (정수 기반) print(df.iloc[0:2]) # 0번째부터 1번째 행까지 반환 (2는 포함되지 않음) """ 출력 결과 A B C row1 1 4 7 row2 2 5 8 """
비교
특징 | loc |
iloc |
기준 | 라벨(Label) | 정수(Integer) |
슬라이싱 범위 | 끝값 포함 | 끝값 미포함 |
사용하면 좋은 경우 | 행/열 이름이 명확할 때 | 정수 위치로 빠르게 참조할 때 |
- 아래의 코드는 동일한 결과를 출력한다.
import pandas as pd data = { 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] } df = pd.DataFrame(data, index=['row1', 'row2', 'row3']) """ 출력 결과 A B C row1 1 4 7 row2 2 5 8 row3 3 6 9 """ print(df.loc['row1', 'A']) print(df.iloc[0, 0]) """ 출력 결과 1 """
참고 사이트
pandas.DataFrame.loc — pandas 2.2.3 documentation
A slice object with labels, e.g. 'a':'f'. Warning Note that contrary to usual python slices, both the start and the stop are included
pandas.pydata.org
pandas.DataFrame.iloc — pandas 2.2.3 documentation
Purely integer-location based indexing for selection by position. Deprecated since version 2.2.0: Returning a tuple from a callable is deprecated. .iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boo
pandas.pydata.org
728x90
728x90
'Programming > Python' 카테고리의 다른 글
[Python] print 문 출력 문자에 색깔 넣는 방법 (ANSI Escape Code) (1) | 2024.11.29 |
---|---|
[Python] Pyinstaller로 패키징할 때 환경 변수 파일(.env) 인식 안되는 문제 해결 방법 (0) | 2024.10.30 |
[Python] 환경 변수 파일(.env) 다루는 방법 (0) | 2024.09.27 |
[Python] try-except 문 사용할 때 에러 발생 시, 전체 에러 정보 표시 방법 (2) | 2024.09.07 |
[Python] 데이터 전처리 할 때 결측값 제거 방법 (Pandas) (1) | 2024.06.21 |
[Python] or 연산자와 | 연산자의 차이 (0) | 2024.05.29 |
[Python] self (0) | 2023.11.29 |
[Python] ORM(Object Relational Mapping) 라이브러리 사용해보기 (SQLAlchemy) (0) | 2023.11.14 |