Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
Let us see how to export a Pandas DataFrame to an Excel file.
Algorithm:
- Create the DataFrame.
- Determine the name of the Excel file.
- Call to_excel() function with the file name to export the DataFrame.
Example 1:
Python3
import
pandas as pd
marks_data
=
pd.DataFrame({
'ID'
: {
0
:
23
,
1
:
43
,
2
:
12
,
3
:
13
,
4
:
67
,
5
:
89
,
6
:
90
,
7
:
56
,
8
:
34
},
'Name'
: {
0
:
'Ram'
,
1
:
'Deep'
,
2
:
'Yash'
,
3
:
'Aman'
,
4
:
'Arjun'
,
5
:
'Aditya'
,
6
:
'Divya'
,
7
:
'Chalsea'
,
8
:
'Akash'
},
'Marks'
: {
0
:
89
,
1
:
97
,
2
:
45
,
3
:
78
,
4
:
56
,
5
:
76
,
6
:
100
,
7
:
87
,
8
:
81
},
'Grade'
: {
0
:
'B'
,
1
:
'A'
,
2
:
'F'
,
3
:
'C'
,
4
:
'E'
,
5
:
'C'
,
6
:
'A'
,
7
:
'B'
,
8
:
'B'
}})
file_name
=
'MarksData.xlsx'
marks_data.to_excel(file_name)
print
(
'DataFrame is written to Excel File successfully.'
)
Output:
DataFrame is written to Excel File successfully.
The Excel file is:
Example 2: We can also first use the ExcelWriter() method to save it.
Python3
import
pandas as pd
cars_data
=
pd.DataFrame({
'Cars'
: [
'BMW'
,
'Audi'
,
'Bugatti'
,
'Porsche'
,
'Volkswagen'
],
'MaxSpeed'
: [
220
,
230
,
240
,
210
,
190
],
'Color'
: [
'Black'
,
'Red'
,
'Blue'
,
'Violet'
,
'White'
]})
datatoexcel
=
pd.ExcelWriter(
'CarsData1.xlsx'
)
cars_data.to_excel(datatoexcel)
datatoexcel.save()
print
(
'DataFrame is written to Excel File successfully.'
)
Output:
DataFrame is written to Excel File successfully.
Like Article
Save Article
17 авг. 2022 г.
читать 2 мин
Часто вас может заинтересовать экспорт фрейма данных pandas в Excel. К счастью, это легко сделать с помощью функции pandas to_excel() .
Чтобы использовать эту функцию, вам нужно сначала установить openpyxl , чтобы вы могли записывать файлы в Excel:
pip install openpyxl
В этом руководстве будет объяснено несколько примеров использования этой функции со следующим фреймом данных:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19],
'assists': [5, 7, 7, 9, 12],
'rebounds': [11, 8, 10, 6, 6]})
#view DataFrame
df
points assists rebounds
0 25 5 11
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6
Пример 1: базовый экспорт
В следующем коде показано, как экспортировать DataFrame по определенному пути к файлу и сохранить его как mydata.xlsx :
df.to_excel (r'C:UsersZachDesktopmydata.xlsx')
Вот как выглядит фактический файл Excel:
Пример 2: Экспорт без индекса
В следующем коде показано, как экспортировать DataFrame в определенный путь к файлу и удалить столбец индекса:
df.to_excel (r'C:UsersZachDesktopmydata.xlsx', index= False )
Вот как выглядит фактический файл Excel:
Пример 3: Экспорт без индекса и заголовка
В следующем коде показано, как экспортировать DataFrame в определенный путь к файлу и удалить столбец индекса и строку заголовка:
df.to_excel (r'C:UsersZachDesktopmydata.xlsx', index= False, header= False )
Вот как выглядит фактический файл Excel:
Пример 4: Экспорт и имя листа
В следующем коде показано, как экспортировать DataFrame в определенный путь к файлу и назвать рабочий лист Excel:
df.to_excel (r'C:UsersZachDesktopmydata.xlsx', sheet_name='this_data')
Вот как выглядит фактический файл Excel:
Полную документацию по функции to_excel() можно найти здесь .
You can export Pandas DataFrame to an Excel file using to_excel.
Here is a template that you may apply in Python to export your DataFrame:
df.to_excel(r'Path where the exported excel will be storedFile Name.xlsx', index=False)
And if you want to export your DataFrame to a specific Excel Sheet, then you may use this template:
df.to_excel(r'Path of excelFile Name.xlsx', sheet_name='Your sheet name', index=False)
Note: you’ll have to install openpyxl if you get the following error:
ModuleNotFoundError: No module named ‘openpyxl’
You may then use PIP to install openpyxl as follows:
pip install openpyxl
In the next section, you’ll see a simple example, where:
- A DataFrame will be created from scratch
- Then, the DataFrame will be exported to an Excel file
Let’s say that you have the following dataset about products and their prices:
product_name | price |
computer | 1200 |
printer | 150 |
tablet | 300 |
monitor | 450 |
The ultimate goal is to export that dataset into Excel.
But before you export that data, you’ll need to create a DataFrame in order to capture this information in Python.
You may then use the following syntax to create the DataFrame:
import pandas as pd data = {'product_name': ['computer', 'printer', 'tablet', 'monitor'], 'price': [1200, 150, 300, 450] } df = pd.DataFrame(data) print(df)
This is how the DataFrame would look like:
product_name price
0 computer 1200
1 printer 150
2 tablet 300
3 monitor 450
Next, you’ll need to define the path where you’d like to store the exported Excel file.
For example, the path below will be used to store the exported Excel file (note that you’ll need to adjust the path to reflect the location where the Excel file will be stored on your computer):
r‘C:UsersRonDesktopexport_dataframe.xlsx’
Notice that 3 components were highlighted in relation to that path:
- In yellow, the ‘r’ character is placed before the path to avoid unicode error
- In blue, the file name to be created is specified. You may type a different file name based on your needs
- In green, the file type is specified. Since we are dealing with an Excel file, the file type would be ‘.xlsx’ for the latest version of Excel
Putting everything together, here is the full Python code to export Pandas DataFrame to an Excel file:
import pandas as pd data = {'product_name': ['computer', 'printer', 'tablet', 'monitor'], 'price': [1200, 150, 300, 450] } df = pd.DataFrame(data) df.to_excel(r'C:UsersRonDesktopexport_dataframe.xlsx', index=False)
Finally, run the above code in Python (adjusted to your path), and you’ll notice that a new Excel file (called export_dataframe) would be created at the location that you specified.
Note that if you wish to include the index, then simply remove “, index=False” from your code.
Additional Resources
You just saw how to export Pandas DataFrame to an Excel file. At times, you may need to export Pandas DataFrame to a CSV file. The concept would be similar in such cases.
You may also want to check the Pandas Documentation for additional information about df.to_excel.
Often you may be interested in exporting a pandas DataFrame to Excel. Fortunately this is easy to do using the pandas to_excel() function.
In order to use this function, you’ll need to first install openpyxl so that you’re able to write files to Excel:
pip install openpyxl
This tutorial will explain several examples of how to use this function with the following DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'points': [25, 12, 15, 14, 19], 'assists': [5, 7, 7, 9, 12], 'rebounds': [11, 8, 10, 6, 6]}) #view DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6
Example 1: Basic Export
The following code shows how to export the DataFrame to a specific file path and save it as mydata.xlsx:
df.to_excel(r'C:UsersZachDesktopmydata.xlsx')
Here’s what the actual Excel file looks like:
Example 2: Export without Index
The following code shows how to export the DataFrame to a specific file path and remove the index column:
df.to_excel(r'C:UsersZachDesktopmydata.xlsx', index=False)
Here’s what the actual Excel file looks like:
Example 3: Export without Index and Header
The following code shows how to export the DataFrame to a specific file path and remove the index column and the header row:
df.to_excel(r'C:UsersZachDesktopmydata.xlsx', index=False, header=False)
Here’s what the actual Excel file looks like:
Example 4: Export and Name the Sheet
The following code shows how to export the DataFrame to a specific file path and name the Excel worksheet:
df.to_excel(r'C:UsersZachDesktopmydata.xlsx', sheet_name='this_data')
Here’s what the actual Excel file looks like:
You can find the complete documentation for the to_excel() function here.
Exporting the data to an Excel file is usually the most preferred and handy way to read and interpret a given set of data by any user. It is possible to export your web scraping or other collected data using python code to export to an Excel file, and that too in very simple steps, by making use of the Pandas library.
Follow the below step-by-step tutorial to learn to write a Pandas DataFrame to an Excel File.
Step 1: Install pandas and openpyxl
As you require to export pandas data frame, it is evident that you must be having the pandas package already installed. If not, run the following pip command to install the Pandas python package on your computer.
Now, to work with Excel file functions in Python, you need to install the openpyxl module using the below pip command.
You can write the DataFrame to Excel File without mentioning any sheet name. The step by step process is given below:
Step 2: Make a DataFrame
- Import Pandas package in your python code/script file.
- Create a dataframe of the data you wish to export and initialize the DataFrame with values for rows and columns.
Python Code:
#import pandas package import pandas as pd # creating pandas dataframe df_cars = pd.DataFrame({'Company': ['BMW', 'Mercedes', 'Range Rover', 'Audi'], 'Model': ['X7', 'GLS', 'Velar', 'Q7'], 'Power(BHP)': [394.26, 549.81, 201.15, 241.4], 'Engine': ['3.0 L 6-cylinder', '4.0 L V8', '2.0 L 4-cylinder', '4.0 L V-8']})
Step 3: Create a Writer Object and Export to Excel File
- Create an Excel Writer Object using the: ExcelWriter() method of pandas package
- Input the name of the output excel file, to which you would like to write our DataFrame with extension. (In our example, we have named our output excel file as ‘converted-to-excel.xlsx’)
# creating excel writer object writer = pd.ExcelWriter('converted-to-excel.xlsx')
- Call to_excel() function on the DataFrame with the Excel Writer passed as an argument to export your data to the Excel file with the already given name and extension.
- Save the writer object to save the Excel file
# write dataframe to excel df_cars.to_excel(writer) # save the excel writer.save() print("DataFrame is exported successfully to 'converted-to-excel.xlsx' Excel File.")
Alternate – Direct Approach
A direct approach to this is by exporting data frame directly to the Excel file, without making use of the ExcelWriter object as shown in the below code sample:
import pandas as pd # creating pandas dataframe from dictionary of data df_cars = pd.DataFrame({'Company': ['BMW', 'Mercedes', 'Range Rover', 'Audi'], 'Model': ['X7', 'GLS', 'Velar', 'Q7'], 'Power(BHP)': [394.26, 549.81, 201.15, 241.4], 'Engine': ['3.0 L 6-cylinder', '4.0 L V8', '2.0 L 4-cylinder', '4.0 L V-8']}) #Exporting dataframe to Excel file df_cars.to_excel("converted-to-excel.xlsx")
Output Excel File
Open the excel file, and you shall see the index, column labels, and row data written to the file.
Bonus Tips
You are not only restricted to only control the excel file name rather with python dataframe exported to an Excel file, but you also have many functionalities available for customization in the pandas package.
You can change the name of the Sheet of the excel file
df.to_excel("output.xlsx", sheet_name='Sheet_name_1')
Use Excel writer to append to an existing excel file
pd.ExcelWriter('output.xlsx', mode='a')
Other options include render Engine, start row, header, index, merge cells, encoding, and many others.
Learn more about all the options available at Pandas official documentation.
Conclusion
I hope you now understand how to export a Pandas dataframe to Excel using the different libraries at hand. Do follow AskPython for more such interesting tutorials.