current position:Home>How to convert pandas data to excel file
How to convert pandas data to excel file
2022-01-30 20:40:26 【Stone sword】
Export data to Excel Files are usually the most preferred and convenient way for any user to read and interpret a set of data . By using Pandas library , It can be used Python The code exports your network search or other collected data to Excel In file , And the steps are very simple .
take Pandas DataFrame Convert to Excel Steps for
Follow these steps to learn how to Pandas Data frame write Excel file .
First step : install pandas and openpyxl
Because you need to export pandas Data frame , Obviously you must have installed pandas package . without , Please run the following pip command , Install... On your computer Pandas python package .
pip install openpyxl
Copy code
Now? , In order to be in Python Use in Excel File functions , You need to use the following pip Command to install openpyxl modular .
pip install openpyxl
Copy code
You can add... Without mentioning any worksheet names DataFrame write in Excel file . Here is a step-by-step process .
The first 2 Step : To make a DataFrame
- In your python Code / Import... From script file Pandas package .
- Create a data framework for the data you want to output , And initialize the data frame with the values of 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']})
Copy code
The first 3 Step : Create a writer object and export it to Excel file
- Use Python Of Excel Writer() Method to create a Excel Writer object . Use pandas Bag ExcelWriter() Method to create a Excel Writing object .
- Input and output Excel The name of the document , You want to take our DataFrame Write to the extension of the file .( In our case , We will output excel The file is named " Convert to excel.xlsx")
# creating excel writer object
writer = pd.ExcelWriter('converted-to-excel.xlsx')
Copy code
- stay DataFrame On the call to_excel() function , take Excel Writer Pass as a parameter , Export your data to a with a given name and extension Excel file .
- Save the writer object to save 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.")
Copy code
Alternative methods -- Direct method
A direct method is to export the data framework directly to Excel file , Instead of using Excel Writer object , As the following code example shows .
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")
Copy code
Output Excel file
open Excel file , You'll see the index 、 Column labels and row data are written to the file .
Tips
You're not limited to controlling excel The name of the document , It's going to be python Export data frame to Excel In file , And in pandas There are also many customizable functions in the package .
You can change excel The name of the worksheet of the file
df.to_excel("output.xlsx", sheet_name='Sheet_name_1')
Copy code
Use Excel writer Append to an existing Excel In the document
pd.ExcelWriter('output.xlsx', mode='a')
Copy code
Other options include rendering engine 、 Start line 、 header 、 Indexes 、 merge cell 、 Coding and many other options .
copyright notice
author[Stone sword],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201302040237675.html
The sidebar is recommended
- Introduction to python (IV) dynamic web page analysis and capture
- leetcode 119. Pascal's Triangle II(python)
- leetcode 31. Next Permutation(python)
- [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
- The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
- Glom module of Python data analysis module (1)
- Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
- Summarize some common mistakes of novices in Python development
- Python libraries you may not know
- [Python crawler] detailed explanation of selenium from introduction to actual combat [2]
guess what you like
-
This is what you should do to quickly create a list in Python
-
On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
-
Python OpenCV image area contour mark, which can be used to frame various small notes
-
How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
-
Initial Python tuple
-
Introduction to Python urllib module
-
Advanced Python Basics: from functions to advanced magic methods
-
Python Foundation: data structure summary
-
Python Basics: from variables to exception handling
-
Python notes (22): time module and calendar module
Random recommended
- Python notes (20): built in high-order functions
- Python notes (17): closure
- Python notes (18): decorator
- Python notes (16): generators and iterators
- Python notes (XV): List derivation
- Python tells you what timing attacks are
- Python -- file and exception
- [Python from introduction to mastery] (IV) what are the built-in data types of Python? Figure out
- Python code to scan code to pay attention to official account login
- [algorithm learning] 1221 Split balanced string (Java / C / C + + / Python / go / trust)
- Python notes (22): errors and exceptions
- Python has been hidden for ten years, and once image recognition is heard all over the world
- Python notes (21): random number module
- Python notes (19): anonymous functions
- Use Python and OpenCV to calculate and draw two-dimensional histogram
- Python, Hough circle transformation in opencv
- A library for reading and writing markdown in Python: mdutils
- Datetime of Python time operation (Part I)
- The most useful decorator in the python standard library
- Python iterators and generators
- [Python from introduction to mastery] (V) Python's built-in data types - sequences and strings. They have no girlfriend, not a nanny, and can only be used as dry goods
- Does Python have a, = operator?
- Go through the string common sense in Python
- Fanwai 4 Handling of mouse events and solutions to common problems in Python opencv
- Summary of common functions for processing strings in Python
- When writing Python scripts, be sure to add this
- Python web crawler - Fundamentals (1)
- Pandas handles duplicate values
- Python notes (23): regular module
- Python crawlers are slow? Concurrent programming to understand it
- Parameter passing of Python function
- Stroke tuple in Python
- Talk about ordinary functions and higher-order functions in Python
- [Python data acquisition] page image crawling and saving
- [Python data collection] selenium automated test framework
- Talk about function passing and other supplements in Python
- Python programming simulation poker game
- leetcode 160. Intersection of Two Linked Lists (python)
- Python crawler actual combat, requests module, python to grab the beautiful wallpaper of a station
- Fanwai 5 Detailed description of slider in Python opencv and solutions to common problems