Python

[파이썬] 데이터프레임 행 반복 처리 - iterrows, itertuples

weweGH 2025. 4. 24. 09:00
반응형

데이터프레임 행 반복 처리
데이터프레임 행 반복 처리


데이터프레임 행 반복 처리 - iterrows, itertuples


들어가며


파이썬에서 데이터프레임의 행을 반복해서 처리하는 작업이 필요할 때 사용하는 iterrows와 itertuples에 대해 소개합니다. 이 글에서 활용할 데이터는 seaborn의 iris 데이터입니다.

import seaborn as sns
df = sns.load_dataset('iris')
df.head()

iris 출력 결과
iris 출력 결과



iterrows


iterrows는 Pandas DataFrame에서 각 행을 반복할 수 있게 해주는 메서드입니다. 이 메서드는 DataFrame의 행을 순차적으로 처리할 때 유용하며, 각 행에 대해 행의 인덱스와 데이터를 반환합니다. 

for index, row in df.iterrows():
    print(f"Index: {index}")
    print(f"species: {row['species']}, sepal_length: {row['sepal_length']}, sepal_width: {row['sepal_width']}\n")

iterrows 출력 결과
iterrows 출력 결과

반응형

itertuples


itertuples는 Pandas 데이터프레임에서 각 행을 namedtuple 형태로 반복하게 해주는 메서드입니다. iterrows와 유사하지만, 성능이 더 뛰어나며 일반적으로 큰 DataFrame을 다룰 때 선호됩니다. 


iterrows와 동일한 결과를 출력한다면 다음과 같습니다. itertuples를 사용하면 각 행을 namedtuple로 반환하므로 속성에 점 표기법으로 접근할 수 있습니다. row의 species 변수를 출력한다면, row.species로 표현합니다.

for row in df.itertuples():
    print(f"Index: {row.Index}")
    print(f"species: {row.species}, sepal_length: {row.sepal_length}, sepal_width: {row.sepal_width}\n")

itertuples 출력 결과
itertuples 출력 결과


index를 제외한 결과를 출력한다면 다음과 같습니다. index=False 옵션을 통해 index를 제외한 결과를 출력합니다.

for row in df.itertuples(index=False):
    print(row)

index 제외 row 출력결과
index 제외 row 출력결과


데이터프레임의 품질을 확인해야 할 때, itertuple을 활용하면 에러 데이터를 빠르고 편리하게 출력할 수 있습니다. 예를 들어 iris 데이터에서 sepal_width가 3.0이면 이상 데이터라고 가정했을 때, 이상 데이터만 출력하는 방법은 다음과 같습니다.

for row in df.itertuples():
    if row.sepal_width == 3.0:
        print(row.Index, ': sepal width check required')

sepal_width 3.0
sepal_width 3.0


전체 코드


## iris dataset

import seaborn as sns
df = sns.load_dataset('iris')
df.head()

# --------------------------------------------------------------------------------- */

## iterrows

# row 출력
for index, row in df.iterrows():
    print(f"Index: {index}")
    print(f"species: {row['species']}, sepal_length: {row['sepal_length']}, sepal_width: {row['sepal_width']}\n")

# --------------------------------------------------------------------------------- */

## itertuples

# row 출력
for row in df.itertuples():
    print(f"Index: {row.Index}")
    print(f"species: {row.species}, sepal_length: {row.sepal_length}, sepal_width: {row.sepal_width}\n")


# row 출력 - index 제외
for row in df.itertuples(index=False):
    print(row)


# row 출력 - 이상 데이터 출력
for row in df.itertuples():
    if row.sepal_width == 3.0:
        print(row.Index, ': sepal width check required')

# --------------------------------------------------------------------------------- */

반응형