Pandas를 사용하여 기존 Excel 파일에 새 시트 추가
Pandas는 Excel 파일 작업을 위한 편리한 인터페이스를 제공합니다. 그러나 새 시트를 기존 파일에 저장할 때 사용자는 종종 문제에 직면합니다. 이 문서에서는 문제를 해결하고 포괄적인 솔루션을 제공합니다.
기존 코드:
제공된 코드는 두 개의 DataFrame을 두 개의 시트에 저장하지만 시트를 잃지 않고 더 많은 시트를 추가하는 데 실패합니다. ExcelWriter 개체를 닫으면 원래 데이터가 발생합니다.
최상의 접근 방식:
이상적인 작업 흐름에는 Excel 파일을 만들고, 일부 데이터를 저장하고, ExcelWriter를 닫은 다음 다시 여는 작업이 포함됩니다. 더 많은 시트를 추가하려면 이 접근 방식은 데이터 보존을 보장합니다.
Openpyxl 통합:
데이터 손실 없이 시트를 추가하기 위해 Pandas는 Openpyxl을 활용할 수 있습니다. Openpyxl을 사용하면 Excel 파일을 직접 조작할 수 있습니다. load_workbook을 사용하여 기존 파일을 로드하고 ExcelWriter의 책으로 설정하면 기존 파일에 영향을 주지 않고 새 시트를 추가할 수 있습니다.
전체 예:
다음은 전체 예:
<code class="python">import pandas as pd import numpy as np from openpyxl import load_workbook path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx" # Generate initial data x1 = np.random.randn(100, 2) df1 = pd.DataFrame(x1) x2 = np.random.randn(100, 2) df2 = pd.DataFrame(x2) # Write initial sheets writer = pd.ExcelWriter(path, engine='xlsxwriter') df1.to_excel(writer, sheet_name='x1') df2.to_excel(writer, sheet_name='x2') writer.close() # Open existing file and add new sheets book = load_workbook(path) writer = pd.ExcelWriter(path, engine='openpyxl') writer.book = book # Generate new data x3 = np.random.randn(100, 2) df3 = pd.DataFrame(x3) x4 = np.random.randn(100, 2) df4 = pd.DataFrame(x4) # Append new sheets df3.to_excel(writer, sheet_name='x3') df4.to_excel(writer, sheet_name='x4') writer.close()</code>
이 코드는 먼저 두 개의 시트를 생성하고 ExcelWriter를 닫습니다. 그런 다음 파일을 다시 열고 Openpyxl을 활용하여 원본 데이터를 보존하면서 두 개의 시트를 더 추가합니다.
위 내용은 Pandas를 사용하여 기존 Excel 파일에 새 시트를 추가하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

forhandlinglargedatasetsinpython, usenumpyarraysforbetterperformance.1) numpyarraysarememory-effic andfasterfornumericaloperations.2) leveragevectorization foredtimecomplexity.4) managemoryusage withorfications data

inpython, listsusedyammoryAllocation과 함께 할당하고, whilempyarraysallocatefixedMemory.1) listsAllocatemememorythanneedInitiality.

Inpython, youcansspecthedatatypeyfelemeremodelerernspant.1) usenpynernrump.1) usenpynerp.dloatp.ploatm64, 포모 선례 전분자.

numpyissentialfornumericalcomputinginpythonduetoitsspeed, memory-efficiency 및 comperniveMathematicaticaltions

contiguousUousUousUlorAllocationScrucialForraysbecauseItAllowsOfficationAndFastElementAccess.1) ItenableSconstantTimeAccess, o (1), DuetodirectAddressCalculation.2) Itimprovesceeffiency theMultipleementFetchespercacheline.3) Itsimplififiesmomorym

slicepaythonlistisdoneusingthesyntaxlist [start : step : step] .here'showitworks : 1) startistheindexofthefirstelementtoinclude.2) stopistheindexofthefirstelemement.3) stepisincrementbetwetweentractionsoftortionsoflists

NumpyAllowsForVariousOperationsOnArrays : 1) BasicArithmeticLikeadDition, Subtraction, A 및 Division; 2) AdvancedOperationsSuchasmatrixmultiplication; 3) extrayintondsfordatamanipulation; 5) Ag

Arraysinpython, 특히 Stroughnumpyandpandas, areestentialfordataanalysis, setingspeedandefficiency


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

WebStorm Mac 버전
유용한 JavaScript 개발 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기
