In this tutorial, we will see how we can save pandas dataframe to Excel files.
Pandas to_excel – Pandas Dataframe to Excel
The to_excel()
method of pandas will save the data frame object as a comma-separated values file having a .csv extension.
Pandas to_excel Syntax:
The official documentation provides the syntax below, We will learn the most commonly used among these in the following sections with an example.
DataFrame.to_excel(excel_writer, sheet_name='Sheet1', na_rep='', float_format=None, columns=None,
header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None,
merge_cells=True, encoding=None, inf_rep='inf', verbose=True, freeze_panes=None))
Let us look at some of the arguments to save the data-frame as an Excel file
Output:
fruit name | sourVSsweet | |
0 | Lemon | Sour |
1 | Grapefruit | Sour |
2 | Orange | Sour |
3 | Raspberry | Sour |
4 | Cherry | Sweet |
5 | Banana | Sweet |
6 | Grapes | Sweet |
7 | Watermelon | Sweet |
8 | Avacado | None |
9 | Strawberry | Sour |
2. Save data-frame to Excel file by changing separator
In this example, we will save the data frame as an excel file by changing the separator to comma (“,”) and saving index as a particular column from the data.
import pandas as pd
fpath = "F:/onlinetutorialspoint/Fruit.xlsx"
data2 = pd.read_excel(fpath,usecols=['Fruit','Sweetness','Soreness'],index_col='Fruit')
data2.to_csv('modified_emp_data2.csv',sep=',',index=True )
Output:
Fruit | Sweetness | Soreness |
Lemon | 1 | 9 |
Grapefruit | 2 | 8 |
Orange | 3 | 7 |
Raspberry | 2 | 8 |
Cherry | 6 | 4 |
Banana | 9 | 1 |
Grapes | 8 | 2 |
Watermelon | 9 | 1 |
Avacado | 1 | 1 |
Strawberry | 5 | 5 |
So we learned about how we can read an excel file and save a data frame as an excel file along with customizations.
References:
- What is Python NumPy Library
- Read CSV file in Pandas
- Pandas to_csv() – Pandas Save Dataframe to CSV file
- Pandas.to_excel
Happy Learning 🙂