엑셀 월별시트분리 통합 python pandas code
월별시트분리
# 엑셀 데이터 파일 경로
file_path = "data/card-use-monthly.xlsx"
# 엑셀 데이터 읽기
df = pd.read_excel(file_path)
# 날짜 형식 보장 및 월 정보 생성
df['승인일자'] = pd.to_datetime(df['승인일자'], errors='coerce')
df['승인월'] = df['승인일자'].dt.month
# 계정과목 분류를 위한 키워드 사전
category_dict = {
'여비교통비': ['주유소', '고속', '철도', '버스', '택시', '교통', 'KTX'],
'복리후생비': ['마트', '편의점', '카페', '백화점', '음식점'],
'접대비': ['한우', '한정식', '횟집', '회식', '호텔'],
'소모품비': ['문구', '다이소', '오피스'],
'통신비': ['SKT', 'KT', 'LGU', '유플러스']
}
# 계정과목 분류 함수
def classify_account(store_name):
for category, keywords in category_dict.items():
if any(keyword in str(store_name) for keyword in keywords):
return category
return '기타'
# 계정과목 컬럼 생성
df['계정과목'] = df['가맹점명'].apply(classify_account)
# 최종 저장할 컬럼 목록
columns_to_save = ['승인일자', '카드사', '가맹점명', '결제금액', '계정과목', '승인월']
# 결과 저장 엑셀 파일
output_file = '월별_카드사용_정리.xlsx'
# 월별 시트 저장
with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
for month in range(1, 13):
month_df = df[df['승인월'] == month][columns_to_save]
sheet_name = f"{month}월"
month_df.to_excel(writer, sheet_name=sheet_name, index=False)
print(f"✅ 엑셀 저장 완료: {output_file}")
# 저장된 엑셀 파일 다시 열어 확인
wb = load_workbook(output_file)
print("\n📄 저장된 시트 목록:", wb.sheetnames)
for sheet in wb.sheetnames:
sheet_df = pd.read_excel(output_file, sheet_name=sheet)
print(f"\n▶ {sheet} 시트 첫 3줄 미리보기:")
print(sheet_df.head(3))
시트 통합
def read_and_combine_sheets(file_path):
"""
엑셀 파일의 모든 시트를 읽어 하나의 데이터프레임으로 결합합니다.
Parameters:
file_path (str): 읽어들일 엑셀 파일 경로
Returns:
pd.DataFrame: 병합된 단일 데이터프레임
"""
with pd.ExcelFile(file_path, engine='openpyxl') as xls:
sheet_names = xls.sheet_names
print(f"📄 시트 목록: {sheet_names}")
df_list = [pd.read_excel(xls, sheet_name=sheet) for sheet in sheet_names]
combined_df = pd.concat(df_list, ignore_index=True)
return combined_df
# 📌 1. 파일 경로 설정
input_file = 'data/card-use-monthly.xlsx'
output_file = '통합_데이터.xlsx'
# 📌 2. 함수 호출: 모든 시트를 하나의 DataFrame으로 결합
merged_df = read_and_combine_sheets(input_file)
print(f"\n✅ 데이터 통합 완료: 총 {len(merged_df)}건")
# 📌 3. 단일 시트 엑셀 파일로 저장
merged_df.to_excel(output_file, sheet_name='통합데이터', index=False)
print(f"✅ 저장 완료: '{output_file}'에 '통합데이터' 시트 생성")