[Python] How to output a pandas table to an excel file

[Python] How to output a pandas table to an excel file

Use the to_excel method to output a DataFrame type table as an excel file.

table of contents

  1. [Install Library](#Install Library)
  2. [Output by specifying the file name](# Output by specifying the file name)
  3. [Output by specifying the sheet name](# Output by specifying the sheet name)
  4. [Hide header](#Hide header)
  5. [Hide index (row name)](#Hide index line name)
  6. Don't show headers and indexes (#Hide headers and indexes)
  7. [Put a blank line at the top](#Put a blank line at the top)
  8. [Put a blank column on the left](#Put a blank column on the left)
  9. [Specify the maximum number of decimal places to display](#Specify the maximum number of decimal places to display)
  10. [Fill NaN with arbitrary value](Fill #nan with arbitrary value)
  11. [What you can do with ExcelWriter and notes](What you can do with #excelwriter and notes)
  12. [Create two or more sheets](#Create two or more sheets)
  13. Add a new sheet to an existing file (#Add a new sheet to an existing file)

## Library installation

Library installation


pip install -U openpyxl
pip install -U xlwt
pip install -U pandas

① openpyxl: Python library for reading and writing xlsx / xlsm / xltx / xltm files

(2) xlwt: Library for writing data and format information to old Excel files (.xls, etc.) (Excel2003 or earlier)

③ A library for data analysis with python. Used for handling table data.


## Table data to write The following table data is output to Excel.

image.png

python


import pandas as pd
import numpy as np

row0 = [0, 1, 2, 3, 4]
row1 = [1, 10, 20, 30, 40]
row2 = [10, 100, 200, 300, 400]
row3 = [np.nan, np.nan, 'aaa', np.nan, np.nan]
row4 = [0.1, 0.12, 0.123, np.nan, 0.12345]

df = pd.DataFrame([row0,row1,row2,row3, row4])
df.columns = ['col0', 'col1', 'col2' ,'col3', 'col4']
df.index = ['row0', 'row1', 'row2', 'row3', 'row4']

df

## Output by specifying the file name `df.to_excel ('file path')` └ "df": Output table data └ "File path": File name is also listed

output


import pandas as pd
df.to_excel('~/desktop/output.xlsx')

Output to the desktop with the name "output.xlsx".

If the sheet name is not specified, it will be "sheet1".

** ▼ Output result ** image.png


## Output by specifying the sheet name Specify the sheet name with the "sheet_name" option.

df.to_excel ('file path', sheet_name ='A') └ "A": Sheet name

Specify the sheet name


import pandas as pd
df.to_excel('~/desktop/output.xlsx', sheet_name='AAA')

Output with the sheet name "AAA".

** ▼ Output result ** image.png


## Don't show header Describe `header = False` in the option.

Or you can use "header = None".

No header


import pandas as pd
df.to_excel('~/desktop/output.xlsx', header=False)

image.png


## Do not display index (row name) Describe ʻindex = False` in the option.

Or you can use "index = None".

No index


import pandas as pd
df.to_excel('~/desktop/output.xlsx', index=None)

image.png


## Don't show headers and indexes

Describe ʻindex = False and header = False` in the options.

No header / index


import pandas as pd
df.to_excel('~/desktop/output.xlsx', index=False, header=False)

image.png


## Put a blank line at the top

Describe startrow = n in the option. └ "n": Number of free lines

** ▼ When n = 3 **

Put a blank line at the top


import pandas as pd
df.to_excel('~/desktop/output.xlsx', startrow=3)

image.png


## Put a blank column on the left

Describe startcol = n in the option. └ "n": Number of empty columns

** ▼ When n = 2 **

Put a blank line at the top


import pandas as pd
df.to_excel('~/desktop/output.xlsx', startcol=2)

image.png


## Specify the maximum number of displayed digits for the decimal point

Describe float_format ='% .nf' in the option. └ "n": Number of digits to display

Specify the maximum number of displayed digits for the decimal point


import pandas as pd
df.to_excel('~/desktop/output.xlsx', float_format='%.2f')

image.png

If n = 2, the 3rd digit is rounded off and displayed up to the 2nd decimal place.


## Fill NaN with any value

Describe na_rep ='A' in the option. └ "A": Value to fill NaN cell

Fill NaN


import pandas as pd
df.to_excel('~/desktop/output.xlsx', na_rep='XXXX')

image.png

What you can do with Excel Writer and notes

If you use the ExcelWriter function and to_excel together, you can output an Excel file with two or more sheets or add a sheet to an existing file.

Official page


** ▼ What you can do ** ・ Create two or more sheets -Add a sheet to an existing file ・ You can set the date format
** ▼ Notes ** -"~" Pointing to the home directory cannot be used in the file path. -When specifying the path with a backslash "/", use "//". (¥\) └ "/" is for escape. -Files opened with Excel Writer need to be closed. └ Use with syntax

Excel Writer error supplement


## Create two or more sheets Use Excel Writer.

How to write


with pd.ExcelWriter('Output destination path.xlsx') as writer:
Table object.to_excel(writer, sheet_name='Sheet name')
Table object 2.to_excel(writer, sheet_name='Sheet name 2')
・
・
・

▼ When outputting two tables, df1 and df2, to one Excel file

Illustration


with pd.ExcelWriter('test.xlsx') as writer:
    df1.to_excel(writer, sheet_name='sheet1')
    df2.to_excel(writer, sheet_name='sheet2')

Create a text.xlsx file in the same directory as the running environment.


## Add a new sheet to an existing file

How to write


with pd.ExcelWriter(''Output destination path.xlsx', mode='a') as writer:
Table object to add.to_excel(writer, sheet_name='Sheet name')

Mode ='a': Add file

▼ Add sheet "sheet3" to the existing file (test.xlsx).

Illustration


with pd.ExcelWriter('test.xlsx', mode='a') as writer:
    df3.to_excel(writer, sheet_name='Sheet3')

Official page list -Pandas.DataFrame.to_excelXlwtOpenpyxlExcelWriter

Recommended Posts

[Python] How to output a pandas table to an excel file
How to read an Excel file (.xlsx) with Pandas [Python]
[Python] How to read excel file with pandas
Try to operate an Excel file using Python (Pandas / XlsxWriter) ①
Try to operate an Excel file using Python (Pandas / XlsxWriter) ②
How to convert Python to an exe file
[Python] How to add rows and columns to a table (pandas DataFrame)
How to read a CSV file with Python 2/3
How to create a JSON file in Python
How to convert JSON file to CSV file with Python Pandas
How to turn a .py file into an .exe file
How to save a table scraped by python to csv
[Python] Concatenate a List containing numbers and write it to an output file.
[Pandas] How to check duplicates and delete duplicates in a table (equivalent to deleting duplicates in Excel)
[Note] How to deal with unicode error and No such file or directory (output table to excel file with pandas)
How to write a Python class
How to convert an array to a dictionary with Python [Application]
How to run a Python file at a Windows 10 command prompt
[Python] How to use Pandas Series
Change the standard output destination to a file in Python
Output to csv file with Python
[GCF + Python] How to upload Excel to GCS and create a new table in BigQuery
Write standard output to a file
How to import a file anywhere you like in Python
Create an Excel file with Python3
How to make a Python package (written for an intern)
Output the specified table of Oracle database in Python to Excel for each file
Python learning basics ~ How to output (display) a character string? ~
[Python] How to change EXCEL file saved in xlsb to xlsx
[Python Kivy] How to create an exe file with pyinstaller
How to use NUITKA-Utilities hinted-compilation to easily create an executable file from a Python script
How to create a config file
How to make a string into an array or an array into a string in Python
[Python] How to get & change rows / columns / values from a table.
How to output the output result of the Linux man command to a file
<Pandas> How to handle time series data in a pivot table
How to format a table using Pandas apply, pivot and swaplevel
[Python] How to store a csv file as one-dimensional array data
Get the formula in an excel file as a string in Python
[ROS2] How to play a bag file with python format launch
[Python] How to convert db file to csv
[Python] Summary of how to use pandas
[Python] How to make a class iterable
python3 How to install an external module
[Python] How to convert a 2D list to a 1D list
Quickly create an excel file with Python #python
[Python] How to invert a character string
How to get a stacktrace in python
How to display multiplication table in python
How to run a Maya Python script
[Python] How to scrape a local html file and output it as CSV using Beautiful Soup
I want to color a part of an Excel string in Python
How to create a Python virtual environment (venv)
How to open a web browser from python
How to clear tuples in a list (Python)
How to embed a variable in a python string
Import Excel file from Python (register to DB)
[Python] Road to a snake charmer (6) Manipulate Pandas
How to crop an image with Python + OpenCV
[python] Create table from pandas DataFrame to postgres
How to generate a Python object from JSON