簡體   English   中英

如何將Pandas Series插入現有Excel文件的特定列中(而不從該文件中刪除內容)?

[英]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')

嘗試這個

  • 打開excel文件並將內容存儲在panda對象中,例如df。
  • 在df ['new column']中創建新列
  • 將值存儲在新列中,現在熊貓擁有您所有的先前值+新列
  • 使用ExcelWriter將df保存到excel文件

PS:打開excel文件並在熊貓中寫入excel文件時,可以選擇打開特定的工作表,即sheet_name=

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM