使用 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-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SublimeText3 Linux新版
SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境