Home > Net >  Insert new Column in Excel (Python)
Insert new Column in Excel (Python)

Time:10-16

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?

CodePudding user response:

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.

CodePudding user response:

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!

  • Related