
DataFrame의 record(or row)를 순회(iteration)하는 방법:
1. iterrows()
각 행을 (index, Series) 형태로 반환:
import pandas as pd
df = pd.DataFrame({
"name": ["Kim", "Lee", "Park"],
"age": [28, 34, 29]
})
for idx, row in df.iterrows():
print(idx, row["name"], row["age"])
- 장점: 직관적, 사용이 간단
- 단점: 각각의 row를
Series로 반환 -> 성능 느림 (특히 큰DataFrame객체의 경우)
각 열 단위로 비슷하게 iteration하는 것으로 iteritems()가 있음.
2. itertuples()
각 row를 namedtuple로 반환.
for row in df.itertuples(index=True):
print(row.Index, row.name, row.age) # naumedtuple은 attribute처럼 접근 가능.
- 장점:
iterrows()보다 빠름 - 단점: 반환값이
tuple이므로 속성 접근 방식 제한적
3. apply()
엄밀히는 순회라기 보다는 각 row 단위로 지정한 function을 적용
즉, row 전체에 대해 인자로 넘겨준 callback function을 적용.
df.apply(lambda row: print(row["name"], row["age"]), axis=1)
- 장점: 빠르고 효율적.
- 단점:
for루프보다는 빠르지만, 여전히 순차적 처리임.
4. 벡터화 접근 (권장)
가능하다면 루프 대신 벡터화 연산을 사용하는 게 성능 최선임.
print(df["name"] + " / " + df["age"].astype(str))
Summary
- 작은 데이터:
iterrows()직관적 - 큰 데이터:
itertuples()읽기 전용. 성능 우수 - 함수적 처리:
apply() - 가장 권장: 루프 대신 벡터화 연산
같이보면 좋은 자료들
https://ds31x.tistory.com/124#%EB%B0%98%EB%B3%B5%EB%AC%B8
[Python] Control Structure and Control Flow
Control structure와 Control Flow란 무엇인가?2025.04.23 - [Python] - [Programming] Control Flow 와 Control Structure [Programming] Control Flow 와 Control StructureAbstraction(추상화)을 통한 이해프로그래밍 언어에서 Abstraction은
ds31x.tistory.com
2024.02.04 - [Python] - [Python] itertools: iterator를 반환.
[Python] itertools: iterator를 반환.
chain(*iterables)arguments 로 복수 개의 iterable 객체를 받음.이들 복수 개의 iterables 들을 합친 하나의 iteartor, chain 객체를 반환함.해당 반환된 객체는 for 문으로 iterate가 가능함.>>> for i in itertools.chain([0,
ds31x.tistory.com
'Python > pandas' 카테고리의 다른 글
| Series : 1D data구조 for Pandas (0) | 2025.10.03 |
|---|---|
| DataFrame객체를 파일로 저장하기-csv-excel-json (0) | 2025.09.26 |
| pandas.read_excel() 함수: (0) | 2025.09.26 |
| [Pandas] 차트 그리기-plot (0) | 2025.09.05 |
| [Pandas] isin() 메서드: 가독성 높은 boolean mask 만들기. (2) | 2025.08.28 |