我已使用熊猫从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列中的值...
答案 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)
尝试一下
PS:在打开excel文件并在熊猫中写入excel文件时,可以选择打开特定的表格,例如sheet_name=