user8950120
user8950120

Reputation:

Writing to a specific range/Column with Pandas

I'm attempting to copy from column Range AP:AR of workbook 1 to Range A:C of workbook 2 through Pandas data frames.

I have successfully read the data frame below in workbook 1, I then want to write this into workbook 2 of the specified range. So AP:AR to AQ:AS.

I have tried:

#df.to_excel(writer, 'AP')

I have also tried the following:

 #df = pd.write_excel(filename, skiprows = 2, parse_cols = 'AP:AR')
pd.writer = pd.ExcelWriter('output.xlsx', columns = 'AP:AR')
pd.writer.save()

For example:

filename ='C:/ workbook 1.xlsx'
df = pd.read_excel(filename, skiprows = 2, parse_cols = 'A:C')

import pandas as pd
writer = pd.ExcelWriter('C:/DRAX/ workbook 2.xlsx')
df.to_excel(writer, 'AQ')
writer.save()
print(df)

It reads correctly, but writes to Cell column ‘B’ instead of AQ.

Upvotes: 1

Views: 4287

Answers (1)

Foxan Ng
Foxan Ng

Reputation: 7151

You have to specify the starting column you want to write the dataframe with the parameter startcol, which is an integer starting from 0:

So you should change the line

df.to_excel(writer, 'AQ')

to

df.to_excel(writer, startcol=42) # AQ has the index of 42

Results:

results

Upvotes: 2

Related Questions