본문 바로가기
PROGRAMMING/Python

[PYTHON] 데이터프레임을 엑셀(excel)에 서로 다른 시트(sheet)로 저장하기

by HYUNHP 2023. 1. 31.
728x90
반응형

안녕하세요, HELLO

파이썬의 판다스 라이브러리는 xlsxwriter라고 불리는 기능을 제공합니다. ExcelWriter는 Microsoft Excel 시트에 데이터 프레임을 활용할 수 있는 클래스입니다. xlsxwriter을 활용해서 데이터프레임을 엑셀(excel)에 서로 다른 시트(sheet)로 저장하는 방법에 대해서 살펴보고자 합니다.

 

추가적으로 위 방법을 활용해서 여러 개의 데이터프레임을 여러 개의 엑셀로 저장하는 방법에 대해서도 살펴보겠습니다.


STEP 1. 'excelwriter', 'to_excel' 설명

 

파이썬에서 데이터프레임을 활용해서 엑셀로 저장하거나 불러올 때는, 텍스트, 숫자, 문자열 및 수식은 모두 ExcelWriter를 사용하여 작성할 수 있습니다. 또한 여러 워크시트에서 사용할 수도 있습니다. 

 

excelwriter을 활용하여, to_excel 매서드로 데이터프레임을 엑셀로 저장할 수 있습니다.

to_excel 메서드는 데이터 프레임을 Excel 파일로 내보내는 데 사용됩니다. 엑셀 파일에 단일 개체를 쓰려면 대상 파일 이름을 지정해야 합니다. 여러 시트에 쓰려면 대상 파일 이름으로 ExcelWriter 개체를 만들고 파일에 써야 하는 시트를 지정해야 합니다. 고유 sheet_name을 지정하여 여러 시트를 작성할 수도 있습니다. 파일에 기록된 모든 데이터에 대한 변경 사항을 저장해야 합니다.


본격적으로 설명하기에 앞서 'excelwriter', 'to_excel'의 핵심 파라미터를 확인해 보겠습니다.

 

pandas.ExcelWriter(path, date_format=None, mode=’w’)
path (str) Path to xls or xlsx or ods file
date_format Format string for dates written into Excel files (e.g. ‘YYYY-MM-DD’).  str, default None
mode {‘w’, ‘a’}, default ‘w’. File mode to use (write or append).
Append does not work with fsspec URLs

'mode' 파라미터를 w, writer로 설정하여, 데이터프레임을 엑셀로써 작업할 수 있습니다.

 

DataFrame.to_excel(excel_writer, sheet_name=’Sheet1′,index=True)
excel_writer path-like, file-like, or ExcelWriter object (new or existing)
sheet_name (str, default ‘Sheet1’). Name of the sheet which will contain DataFrame
index (bool, default True). Write row names (index)

 

반응형

 

파라미터를 설정해서 데이터를 입력하면, 아래와 같이 엑셀에 서로 다른 시트(sheet)로 저장할 수 있습니다.

# IMPORT LIBRARY
import pandas as pd
 
# CREATE DATAFRAME 1
data_frame1 = pd.DataFrame({'NAME': ['DOG', 'CAT', 'BIRD',
                                       'Dragon', 'Musk', 'FISH'],
                            'AGE': [20, 30, 15, 10, 50, 40]})
 
# CREATE DATAFRAME 2
data_frame2 = pd.DataFrame({'CODE': ['0101', '2200', '0333',
                                           '4555', '5322', '6511'],
                            'DIGIT': [200, 310, 115, 110, 55, 45]})
 
# CREATE DATAFRAME 3
data_frame3 = pd.DataFrame({'FOODS': ['Cakes', 'biscuits', 'muffins',
                                            'Rusk', 'puffs', 'cupcakes'],
                            'PRICE': [120, 130, 159, 310, 150, 140]})
 
print(data_frame1)
print(data_frame2)
print(data_frame3)
 
# create a excel writer object
with pd.ExcelWriter("./name_excel_out.xlsx") as writer:
   
    # use to_excel function and specify the sheet_name and without index
    data_frame1.to_excel(writer, sheet_name="ANIMAL", index=False)
    data_frame2.to_excel(writer, sheet_name="CODES", index=False)
    data_frame3.to_excel(writer, sheet_name="FOODS", index=False)

# create a excel writer object
with pd.ExcelWriter("./name_excel_with.xlsx") as writer:
   
    # use to_excel function and specify the sheet_name and with index
    data_frame1.to_excel(writer, sheet_name="ANIMAL", index=True)
    data_frame2.to_excel(writer, sheet_name="CODES", index=True)
    data_frame3.to_excel(writer, sheet_name="FOODS", index=True)

 

이때, index를 False/True 설정에 따라 아래와 같이 index를 저장 또는 저장 안 하게 됩니다.

 

without and with index

 

 

추가적으로, 여러 개의 데이터프레임을 여러 개의 엑셀 파일로 저장하고 싶은 경우에는, with 바깥에 반복문 (loop function)을 설정하면 됩니다.

 

참고로, 반복문 안에서 writer.close로 writer를 종료하고, 새로운 데이터프레임을 writer로 open 하면, 위치값을 설정할 수 없다는 에러가 발생하게 됩니다. 이때는 writer.close를 제거하면 에러가 해결됩니다.

 

bool_lst = [False, True]


for bool in bool_lst:
    # create a excel writer object
    with pd.ExcelWriter(f"./save/name_excel_{str(bool)}.xlsx") as writer:
    
        # use to_excel function and specify the sheet_name and without index
        data_frame1.to_excel(writer, sheet_name="ANIMAL", index=bool)
        data_frame2.to_excel(writer, sheet_name="CODES", index=bool)
        data_frame3.to_excel(writer, sheet_name="FOODS", index=bool)
    print(f'{str(bool)} saved.')

print(f'\nDONE.')


'''
False saved.
True saved.

DONE.
'''

 

save done


■ 마무리

'데이터프레임을 엑셀(excel)에 서로 다른 시트(sheet)로 저장하기'에 대해서 알아봤습니다.

좋아요댓글 부탁드리며,

오늘 하루도 즐거운 날 되시길 기도하겠습니다 :)

감사합니다.

반응형

댓글