Insert new Column in Excel (Python)

Question:

I have a python code wherein I take certain data from an excel and work with that data. Now I want that at the end of my code in the already existing Excel table a new column named XY is created. What would be your approach to this?

Asked By: jaayjoo

||

Answers:

The easiest way get the right code is to record a macro in Excel. Go to your table in Excel, command ‘Record macro’ and manually perform required actions. Then command ‘Stop recording’ and go to VBA to discover the code. Then use the equivalent code in your Python app.

Answered By: rotabor

If you’re using pandas to perform operations on the data, and you have it loaded as a df, just add:

import pandas as pd
import numpy as np

# Generating df with random numbers to show example
df = pd.DataFrame(np.random.randint(
    0, 100, size=(15, 4)), columns=list('ABCD'))

print(df.head())
# Adding the empty column
df['xy'] = ''
print(df.head())

#exporting to excel
df.to_excel( FileName.xlsx, sheetname= 'sheet1')

This will add an empty column to the df, with the top cell labelled xy. If you want any values in the column, you can replace the empty ” with a list of whatever.
Hope this helps!

Answered By: Ryan Bowser
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.