python logo

write excel file in python pandas


Python hosting: Host, run, and code Python in the cloud!

Creating Excel files is an essential task for data analysts and researchers. With Python’s Pandas library, this process is straightforward and efficient. In this article, we’ll guide you through creating an Excel file using Python’s Pandas.

Related Course: Data Analysis with Python Pandas

Generating an Excel File with Pandas
To begin with, we’ll need to import necessary components from the Pandas library. Specifically, we’ll be using the ExcelWriter and ExcelFile classes.

Here’s a simple example where we create a DataFrame from two lists and save it to an Excel file:


df = pd.DataFrame({'a':[1,3,5,7,4,5,6,4,7,8,9],
'b':[3,5,6,2,4,6,7,8,7,8,9]})

In this example, ‘a’ and ‘b’ are column names, while the lists provide the data for these columns.

Once our DataFrame is ready, we can write it to an Excel file like this:


writer = ExcelWriter('Pandas-Example2.xlsx')
df.to_excel(writer,'Sheet1',index=False)
writer.save()

If you prefer to see the entire code in one block, here it is:


import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import numpy as np

df = pd.DataFrame({'a':[1,3,5,7,4,5,6,4,7,8,9],
'b':[3,5,6,2,4,6,7,8,7,8,9]})

writer = ExcelWriter('Pandas-Example2.xlsx')
df.to_excel(writer,'Sheet1',index=False)
writer.save()

As an outcome of executing the above code, you’ll have an Excel file that looks like this:
write excel pandas

Interested in reading more about Pandas? Navigate back here.






Leave a Reply: