판다스에서 많이 사용하는 DataFrame.loc, DataFrame.iloc 

 

둘의 차이는 '무엇'을 기준으로 행/열을 찾느냐

pandas.DataFrame.loc

loc의 경우 .index/column 의 이름을 찾는다.

import pandas as pd

df = pd.DataFrame(
    {
        "name": ["A", "B", "C", "D"],
        "score": [80, 90, 70, 95]
    },
    index=[10, 20, 30, 40]
)

print(df)

>>>
   name  score
10    A     80
20    B     90
30    C     70
40    D     95

df.loc[20]

>>>
name      B
score    90

# index label 이 20인 행을 찾음.

df.loc[20:30]

>>>
   name  score
20    B     90
30    C     70
# .loc의 slicing의 경우 양 끝값 포함

df.loc[20, "score"]

>>>
90

# index가 20인 행이거니 column이 socre인 열 출력

 

pandas.DataFrame.iloc

iloc 의 경우 실제 위치를 찾는다.

import pandas as pd

df = pd.DataFrame(
    {
        "name": ["A", "B", "C", "D"],
        "score": [80, 90, 70, 95]
    },
    index=[10, 20, 30, 40]
)

print(df)

>>>
   name  score
10    A     80
20    B     90
30    C     70
40    D     95

df.iloc[1] # 두번쨰 행
>>>
name      B
score    90

# 여기서 1은 index label이 아니라 0부터 세었을때 1번 위치 즉 2번째 행

df.iloc[1, 1] #두번째 행, 두번째 열 
>>>
90

#########################################################
           column position
              0       1
           name    score
position 0   A       80      <- index label 10
position 1   B       90      <- index label 20
position 2   C       70      <- index label 30
position 3   D       95      <- index label 40
##########################################################

 

따라서 아래와 같은경우 loc 과 iloc이 같은 값 반환

df.loc[20, "score"]
>>> 90
df.iloc[1, 1]
>>> 90

 

loc과는 다르게 iloc의 경우 python의 일반적인 slicing 규칙을 따름.

 

df.iloc[1:3]
>>>
   name  score
20    B     90
30    C     70

 

 

Boolean 을 이용한 loc

import pandas as pd

df = pd.DataFrame(
    {
        "name": ["A", "B", "C", "D"],
        "score": [80, 90, 70, 95]
    },
    index=[10, 20, 30, 40]
)

print(df)

>>>
   name  score
10    A     80
20    B     90
30    C     70
40    D     95

# 먼저 
df["score"] > 80
>>>
10    False
20     True
30    False
40     True
Name: score, dtype: bool

df.loc[df["score"] > 80]
>>>
   name  score
20    B     90
40    D     95

 

'Python > pandas' 카테고리의 다른 글

Pandas- DataFrame.duplicated()  (0) 2026.08.26
Pandas - read_csv() -text파일, csv파일 불러오기  (0) 2026.04.07

+ Recent posts