[英]How to append a pandas dataframe to an excel sheet
嗨,我已經看到了更復雜問題的解決方案,但我正在嘗試執行以下操作:
Append 到 dataframe 到 excel 表。 我有一個 excel 文件,其中包含以下數據:
# Create Initial Excel
data = [['tom', 10,1,'a'], ['matt', 15,5,'b'],['nick', 18,2,'b'],['luke', 12,6,'b'],['geoff', 20,10,'a']]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Attempts','Score','Category'])
df
Name Attempts Score Category
0 tom 10 1 a
1 matt 15 5 b
2 nick 18 2 b
3 luke 12 6 b
4 geoff 20 10 a
df.to_excel('Excel.xlsx',index=False)
每周我都會以以下形式獲得新數據:
#New Dataframe
data2 = [['mick', 10,1,'a'], ['matt', 15,5,'b'],['jim', 18,2,'b'],['mark', 12,6,'b'],['geoff', 20,10,'a']]
df2 = pd.DataFrame(data2, columns = ['Name', 'Attempts','Score','Category'])
df2
Name Attempts Score Category
0 mick 10 1 a
1 matt 15 5 b
2 jim 18 2 b
3 mark 12 6 b
4 geoff 20 10 a
我已經嘗試了以下 append 電子表格數據下的新數據:
#Append DF2
with pd.ExcelWriter('Excel.xlsx',
mode='a') as writer:
df2.to_excel(writer,'Sheet1',index=False,header=False)
但它已附加到新工作表?
我只是希望添加到我的 excel 以便它出現:
Name Attempts Score Category
0 tom 10 1 a
1 matt 15 5 b
2 nick 18 2 b
3 luke 12 6 b
4 geoff 20 10 a
0 tom 10 1 a
1 matt 15 5 b
2 nick 18 2 b
3 luke 12 6 b
4 geoff 20 10 a
我在這里找到了我的答案append dataframe 到 excel 和 Z3A43B4F88325D24022C0EFA9的具體問題
from openpyxl import load_workbook
path = "Excel.xlsx"
book = load_workbook(path)
writer = pandas.ExcelWriter("Excel.xlsx", engine='openpyxl')
writer.book = book
writer.sheets = {ws.title: ws for ws in book.worksheets}
df2.to_excel(writer, startrow=writer.sheets['Sheet1'].max_row, index = False,header= False)
writer.save()
您可以在此處嘗試一種方法,此答案中提到了類似的方法。 我的建議是首先連接您的 2 個數據幀,然后寫入 Excel 文件,而不是嘗試合並 Excel 文件。
import pandas as pd
# Create Initial Excel
data = [['tom', 10,1,'a'], ['matt', 15,5,'b'],['nick', 18,2,'b'],['luke', 12,6,'b'],['geoff', 20,10,'a']]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Attempts','Score','Category'])
#New Dataframe
data2 = [['mick', 10,1,'a'], ['matt', 15,5,'b'],['jim', 18,2,'b'],['mark', 12,6,'b'],['geoff', 20,10,'a']]
df2 = pd.DataFrame(data2, columns = ['Name', 'Attempts','Score','Category'])
# Prepare a list of the dataframes, needed for the concat method
all_df = [df, df2]
out_df = pd.concat(all_df).reset_index(drop=True)
# Write concatenated dataframes to Excel
out_df.to_excel("Combined.xlsx", index=False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.