[英]How to insert a Pandas Series into a specific column of an existing Excel file (without deleting content from that file)?
I have imported the following data from Excel with pandas: 我已经使用熊猫从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 |
|-------+------------+----------|
Then I created the following Series ( D
) in pandas: 然后,我在熊猫中创建了以下系列( 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 |
|----------|
How could I insert the Series D
in the column D of sht (the "Table" sheet of my spreadsheet)? 如何将D
系列插入sht的D
列(电子表格的“表格”表)?
I tried: 我试过了:
writer = pd.ExcelWriter(path, engine='openpyxl')
K.to_excel(writer,'Table', startrow=0, startcol=4, header=False, index=False)
writer.save()
But it deletes all the other tabs from my spreadsheet and also erases the values in the A:C columns of my spreadsheet... 但这会从电子表格中删除所有其他标签,并且还会删除电子表格的A:C列中的值...
The pd.ExcelWriter
and .to_excel
method in pandas overwrite the existing file. 大熊猫中的pd.ExcelWriter
和.to_excel
方法将覆盖现有文件。 You are not modifying the existing file, but are deleting it and writing a new file with the same name. 您不是要修改现有文件,而是要删除它并写入具有相同名称的新文件。
If you want to write to an existing excel file, you probably want to use openpyxl
. 如果要写入现有的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')
Try this 尝试这个
PS:while opening excel file and writing excel file in pandas there is option to open a specific sheet ie sheet_name=
PS:打开excel文件并在熊猫中写入excel文件时,可以选择打开特定的工作表,即sheet_name=
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.