简体   繁体   中英

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:

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 = 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)?

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...

The pd.ExcelWriter and .to_excel method in pandas overwrite the existing file. 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 .

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

  • Open excel file and store contents in panda object lets say df.
  • Create the new column in df['new column']
  • Store the value in the new column,now panda has all ur previous values + the new column
  • Save the df to excel file using ExcelWriter

PS:while opening excel file and writing excel file in pandas there is option to open a specific sheet ie sheet_name=

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM