![](/img/trans.png)
[英]Insert pandas Series or DataFrame column into existing Excel file's first empty column (with OpenPyXL?)
[英]How to insert a Pandas Series into a specific column of an existing Excel file (without deleting content from that file)?
我已經使用熊貓從Excel導入了以下數據:
import pandas as pd
sht = pd.read_excel(path, 'Table', index_col=None, header=None, usecols = "A:C")
sht.head()
|-------+------------+----------|
| jon | tyrion | daenerys |
| sansa | cersei | rhaegar |
| arya | jaime | 0 |
| bran | tywin | 0 |
| robb | 0 | 0 |
| 0 | 0 | 0 |
|-------+------------+----------|
然后,我在熊貓中創建了以下系列( D
):
D = pd.Series((sht[sht!=0]).values.flatten()).dropna().reset_index(drop=True)
D
|----------|
| jon |
| tyrion |
| daenerys |
| sansa |
| cersei |
| rhaegar |
| arya |
| jaime |
| bran |
| tywin |
| rob |
|----------|
如何將D
系列插入sht的D
列(電子表格的“表格”表)?
我試過了:
writer = pd.ExcelWriter(path, engine='openpyxl')
K.to_excel(writer,'Table', startrow=0, startcol=4, header=False, index=False)
writer.save()
但這會從電子表格中刪除所有其他標簽,並且還會刪除電子表格的A:C列中的值...
大熊貓中的pd.ExcelWriter
和.to_excel
方法將覆蓋現有文件。 您不是要修改現有文件,而是要刪除它並寫入具有相同名稱的新文件。
如果要寫入現有的excel文件,則可能要使用openpyxl
。
import openpyxl
# open the existing file
wb = openpyxl.load_workbook('myfile.xlsx')
# grab the worksheet. my file has 2 sheets: A-sheet and B-sheet
ws = wb['A-sheet']
# write the series, D, to the 4th column
for row, v in enumerate(D, 1):
ws.cell(row, 4, v)
# save the changes to the workbook
wb.save('myfile.xlsx')
嘗試這個
PS:打開excel文件並在熊貓中寫入excel文件時,可以選擇打開特定的工作表,即sheet_name=
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.