찾다
백엔드 개발파이썬 튜토리얼Pandas를 사용하여 기존 Excel 파일에 새 시트를 추가하는 방법은 무엇입니까?

How to Append New Sheets to Existing Excel Files Using Pandas?

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
목록과 배열 사이의 선택은 큰 데이터 세트를 다루는 파이썬 응용 프로그램의 전반적인 성능에 어떤 영향을 미칩니 까?목록과 배열 사이의 선택은 큰 데이터 세트를 다루는 파이썬 응용 프로그램의 전반적인 성능에 어떤 영향을 미칩니 까?May 03, 2025 am 12:11 AM

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

Python의 목록 대 배열에 대한 메모리가 어떻게 할당되는지 설명하십시오.Python의 목록 대 배열에 대한 메모리가 어떻게 할당되는지 설명하십시오.May 03, 2025 am 12:10 AM

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

파이썬 어레이에서 요소의 데이터 유형을 어떻게 지정합니까?파이썬 어레이에서 요소의 데이터 유형을 어떻게 지정합니까?May 03, 2025 am 12:06 AM

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

Numpy 란 무엇이며 Python의 수치 컴퓨팅에 중요한 이유는 무엇입니까?Numpy 란 무엇이며 Python의 수치 컴퓨팅에 중요한 이유는 무엇입니까?May 03, 2025 am 12:03 AM

numpyissentialfornumericalcomputinginpythonduetoitsspeed, memory-efficiency 및 comperniveMathematicaticaltions

'연속 메모리 할당'의 개념과 배열의 중요성에 대해 토론하십시오.'연속 메모리 할당'의 개념과 배열의 중요성에 대해 토론하십시오.May 03, 2025 am 12:01 AM

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

파이썬 목록을 어떻게 슬라이스합니까?파이썬 목록을 어떻게 슬라이스합니까?May 02, 2025 am 12:14 AM

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

Numpy Array에서 수행 할 수있는 일반적인 작업은 무엇입니까?Numpy Array에서 수행 할 수있는 일반적인 작업은 무엇입니까?May 02, 2025 am 12:09 AM

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

파이썬으로 데이터 분석에 어레이가 어떻게 사용됩니까?파이썬으로 데이터 분석에 어레이가 어떻게 사용됩니까?May 02, 2025 am 12:09 AM

Arraysinpython, 특히 Stroughnumpyandpandas, areestentialfordataanalysis, setingspeedandefficiency

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

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

뜨거운 도구

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 영어 버전

SublimeText3 영어 버전

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

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기