카테고리 없음
컬럼 값 비교
유키공
2025. 6. 27. 12:12
import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
# 🔹 파일 경로
file_path = '원본.xlsx'
# 1. pandas로 데이터 읽기
df = pd.read_excel(file_path)
# 기준 데이터 (a, b)
left = df[['a', 'b']].dropna(subset=['a']).copy()
left['a_clean'] = left['a'].astype(str).str.strip().str.lower()
left['b_clean'] = left['b'].astype(str).str.strip().str.lower()
# 비교 대상 데이터 (c, d)
right = df[['c', 'd']].dropna(subset=['c']).copy()
right['c_clean'] = right['c'].astype(str).str.strip().str.lower()
right['d_clean'] = right['d'].astype(str).str.strip().str.lower()
# 2. 키 기준으로 내부 조인 (모든 조합 비교)
merged = pd.merge(left, right, left_on='a_clean', right_on='c_clean', how='inner')
# 3. 비교 결과
# key: c_clean
# 값이 일치하는 c_clean은 흰색, 불일치하는 c_clean은 노란색 대상
color_map = {} # key = (c값, d값), value = 'white' or 'yellow'
for _, row in merged.iterrows():
key = (row['c'], row['d']) # 실제 표시용 키
if row['b_clean'] == row['d_clean']:
color_map[key] = 'white'
else:
color_map[key] = 'yellow'
# 4. openpyxl 로드
wb = load_workbook(file_path)
ws = wb.active
# 5. 색상 정의
fill_yellow = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
fill_none = PatternFill(fill_type=None) # 색 제거용
# 6. C/D 열에서 색칠
for row in range(2, ws.max_row + 1):
c_val = ws[f"C{row}"].value
d_val = ws[f"D{row}"].value
key = (c_val, d_val)
if key in color_map:
if color_map[key] == 'yellow':
ws[f"D{row}"].fill = fill_yellow
else:
ws[f"D{row}"].fill = fill_none # 흰색 처리
# 7. 저장
wb.save(file_path)
print("✅ 완료: 중복 키 처리 포함해 D 셀 색칠/색 제거 완료")