如何将Pandas系列插入现有Excel文件的特定列中(而不从该文件中删除内容)?

时间:2018-09-16 16:57:43

标签: python python-3.x pandas openpyxl xlsxwriter

我已使用熊猫从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列中的值...

2 个答案:

答案 0 :(得分:1)

pandas中的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')

答案 1 :(得分:0)

尝试一下

  • 打开excel文件并将内容存储在panda对象中,例如df。
  • 在df ['new column']中创建新列
  • 将值存储在新列中,现在熊猫拥有您所有的先前值+新列
  • 使用ExcelWriter将df保存为excel文件

PS:在打开excel文件并在熊猫中写入excel文件时,可以选择打开特定的表格,例如sheet_name=