Before you begin, ensure that you have the Pandas library installed. Additionally, you will need the openpyxl
or xlsxwriter
library to write to Excel format.Converting a Pandas DataFrame to an Excel file is a straightforward process that enhances the shareability and accessibility of your data.
You can install them using pip:
pip install pandas openpyxl
# or
pip install pandas xlsxwriter
Creating a Sample DataFrame
First, let’s create a DataFrame with some sample data:
import pandas as pd
# Sample data for freshers.in Learning
data = {
'Name': ['Sachin', 'Manju', 'Ram', 'Raju', 'David', 'Freshers_in', 'Wilson'],
'Age': [32, 29, 35, 40, 28, 22, 33],
'City': ['Mumbai', 'Bangalore', 'Chennai', 'Delhi', 'New York', 'Los Angeles', 'San Francisco']
}
df = pd.DataFrame(data)
Converting DataFrame to Excel
Using to_excel() Method
The to_excel()
method in Pandas allows you to write DataFrame objects to Excel files. Here’s how you can use it:
Basic Conversion
# Converting DataFrame to Excel
df.to_excel('output.xlsx', index=False)
In this example, the DataFrame df
is converted to an Excel file named output.xlsx
. The index=False
parameter is used to prevent writing row indices into the Excel file.
Customizing the Excel Output
You can customize the output by specifying sheet names, starting row/column, and even the Excel engine to be used.
Example with Customization:
# Writing to a specific sheet and excluding the header
df.to_excel('output.xlsx', sheet_name='Sample Data', startrow=1, startcol=1, header=False, engine='xlsxwriter')
This will create an Excel file with the DataFrame data starting from the second row and second column in a sheet named ‘Sample Data’.
Reading the Excel File (Verification)
To verify that the DataFrame has been correctly written to the Excel file, you can read it back:
# Reading the Excel file
read_df = pd.read_excel('output.xlsx')
print(read_df)