728x90
요약
- 문제점: 단순 column 방향 concat 시 중복 column이 생김
- 해결 방법: intersection()으로 겹치는 column을 찾아 제거 후 concat
- 장점: row가 동일하다는 가정 하에 column이 깔끔하게 합쳐짐
목표
예를 들어, 두 개의 DataFrame이 있다고 가정.
import pandas as pd
df1 = pd.DataFrame({
"id": [1, 2, 3],
"score": [10, 20, 30],
"name": ["A", "B", "C"]
})
df2 = pd.DataFrame({
"id": [1, 2, 3],
"score": [10, 20, 30],
"rank": [1, 2, 3]
})
우리가 원하는 결과는 두 DataFrame을 횡방향(column 방향)으로 합치되, 중복된 열(id, score)은 한 번만 남기는 것.
id score name rank
0 1 10 A 1
1 2 20 B 2
2 3 30 C 3
문제 상황
단순히 pandas.concat()만 사용하면 아래처럼 중복된 column이 그대로 나타남.
result = pd.concat([df1, df2], axis=1)
print(result)
출력 결과:
id score name id score rank
0 1 10 A 1 10 1
1 2 20 B 2 20 2
2 3 30 C 3 30 3
해결 방법
DataFrame.columns.intersection()과 drop() 메서드를 이용해 중복 column을 제거한 후 concat 하면 됨.
# 중복 column 제거 후 column 방향 결합
common_cols = df1.columns.intersection(df2.columns) # 중복 column 찾기
df2_non_overlap = df2.drop(columns=common_cols) # df2에서 겹치는 column 제거
result = pd.concat([df1, df2_non_overlap], axis=1)
print(result)
출력 결과:
id score name rank
0 1 10 A 1
1 2 20 B 2
2 3 30 C 3
반응형
'Study' 카테고리의 다른 글
| 통계검정 테이블 표기 예시 (0) | 2025.08.25 |
|---|---|
| Cross-Validation에서 각 Fold별 성능을 표시하는 방법들 (0) | 2025.08.19 |
| 민감도(Sensitivity) 와 특이도 (Specificity) 관계 (0) | 2025.07.28 |
| ngrok 에러 해결 방안 (Failed to complete tunnel connection) (0) | 2021.07.11 |
| TypeError: super(type, obj): obj must be an instance or subtype of type (0) | 2020.01.09 |