반응형
DataFrame 목록을 하나의 Excel 스프레드 시트로 내보내려면 어떻게해야합니까?
참고
If passing an existing ExcelWriter object, then the sheet will be added to the existing workbook. This can be used to save different 하나의 통합 문서에 대한 DataFrames
작성기 = ExcelWriter ( 'output.xlsx')
df1.to_excel(writer, 'sheet1')
df2.to_excel(writer, 'sheet2')
writer.save ()
그 후 다음과 같이 DataFrame 목록을 하나의 스프레드 시트에 저장하는 함수를 작성할 수 있다고 생각했습니다.
from openpyxl.writer.excel import ExcelWriter
def save_xls(list_dfs, xls_path):
writer = ExcelWriter(xls_path)
for n, df in enumerate(list_dfs):
df.to_excel(writer,'sheet%s' % n)
writer.save()
그러나 (각각이 to_excel
을 개별적으로 저장할 수있는 두 개의 작은 DataFrame 목록이있는 경우) 예외가 발생합니다 (편집 : 트레이스 백 제거됨) :
AttributeError: 'str' object has no attribute 'worksheets'
해결 방법
Pandas 고유의 ExcelWriter
클래스를 사용해야합니다.
from pandas import ExcelWriter
# from pandas.io.parsers import ExcelWriter
그러면 save_xls
함수가 예상대로 작동합니다.
def save_xls(list_dfs, xls_path):
with ExcelWriter(xls_path) as writer:
for n, df in enumerate(list_dfs):
df.to_excel(writer,'sheet%s' % n)
writer.save()
참조 페이지 https://stackoverflow.com/questions/14225676
반응형
'파이썬' 카테고리의 다른 글
파이썬 Windows에서 fcntl 대체 (0) | 2021.01.29 |
---|---|
파이썬 Python : if 문에서 RegEx를 사용하는 방법은 무엇입니까? (0) | 2021.01.29 |
파이썬 Python의 중첩 된 JSON 사전 내에서 값 찾기 (0) | 2021.01.29 |
파이썬 Python-OR 함수를 올바르게 사용 (0) | 2021.01.28 |
파이썬 목록에서 NoneType 요소를 제거하는 네이티브 Python 함수? (0) | 2021.01.28 |
댓글