Create Excel file with Python + similarity matrix

Introduction

There are several libraries for creating Excel files in Python, but XlsxWriter is recommended for the following reasons.

Installation

$ pip install xlsxwriter

Basic usage

Official sample translated into Japanese as appropriate

If you write like this

xlsxwriter_demo.py


#Create new files and worksheets
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()

#Change the width of column A
worksheet.set_column('A:A', 20)

#Added format to make it bold
bold = workbook.add_format({'bold': True})

#Writing text
worksheet.write('A1', 'Hello')

#Writing text and applying formatting
worksheet.write('A2', 'World', bold)

#Write a number (specify the cell address with a number)
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)

#Insert image
worksheet.insert_image('B5', 'logo.png')

workbook.close()

Will be like this

demo.png

Creating a similarity matrix

Just a personal note from here.

Maybe you can do it with numpy, scipy, matplotlib, but the one that came to my mind was xlsxwriter. The resulting sauce looks like this.

sim_matrix.py


# -*- coding: utf-8 -*-
import xlsxwriter
from xlsxwriter.utility import xl_rowcol_to_cell, xl_range_abs

#Create workbooks and worksheets
wb = xlsxwriter.Workbook("sim_matrix.xlsx")
ws = wb.add_worksheet("similarity matrix")

#Set data cell size
for i in range(5):
    ws.set_row(i, 40.5)
    ws.set_column(i, i, 6.0)

#Data entry
data = [[1.00, 0.15, 0.09, 0.01, 0.02],
        [0.15, 1.00, 0.12, 0.06, 0.03],
        [0.09, 0.12, 1.00, 0.08, 0.01],
        [0.01, 0.06, 0.08, 1.00, 0.05],
        [0.02, 0.03, 0.01, 0.05, 1.00]]
for i in range(5):
    for j in range(5):
        ws.write_number(i, j, data[i][j])

#Find the maximum and minimum values excluding diagonal elements using an array formula
data_field = xl_range_abs(0, 0, 4, 4)
ws.write_string(0, 6, "max sim")
max_formula = '{{=MAX(IF(ROW({0})=COLUMN({0}),"",{0}))}}'.format(data_field)
ws.write_formula(0, 7, max_formula)
ws.write_string(1, 6, "min sim")
min_formula = '{{=MIN(IF(ROW({0})=COLUMN({0}),"",{0}))}}'.format(data_field)
ws.write_formula(1, 7, min_formula)

#Apply color scale using conditional formatting
max_cell = xl_rowcol_to_cell(0, 7, row_abs=True, col_abs=True)
min_cell = xl_rowcol_to_cell(1, 7, row_abs=True, col_abs=True)
props = {
    "type": "2_color_scale",
    "max_color": "#FF6347", # tomato
    "min_color": "#FFFFE0", # lightyellow
    "max_type": "formula",
    "min_type": "formula",
    "max_value": max_cell,
    "min_value": min_cell}
ws.conditional_format(0, 0, 4, 4, props)

#writing
wb.close()

Such a file is output.

xlsxwriter_sim_matrix.png

Recommended Posts

Create Excel file with Python + similarity matrix
Create an Excel file with Python3
Quickly create an excel file with Python #python
Excel with Python
Handle Excel with python
Operate Excel with Python (1)
Operate Excel with Python (2)
[Python] How to read excel file with pandas
Create a Photoshop format file (.psd) with python
Operate Excel with Python openpyxl
Let's run Excel with Python
Create 3d gif with python3
[Python] Create a Tkinter program distribution file with cx_Freeze
Create a directory with python
Download csv file with python
Create xlsx file with XlsxWriter
Create a 2d CAD file ".dxf" with python [ezdxf]
[Python] Create a file & folder path specification screen with tkinter
[Python Kivy] How to create an exe file with pyinstaller
How to read an Excel file (.xlsx) with Pandas [Python]
solver> Link> Solve Excel Solver with python
Extract the xz file with python
Matrix representation with Python standard input
Create Awaitable with Python / C API
[Python] Write to csv file with Python
[Automation with python! ] Part 1: Setting file
Implemented file download with Python + Bottle
Create folders from '01' to '12' with python
Output to csv file with Python
Create a virtual environment with Python!
Let's play with Excel with Python [Beginner]
Handle Excel CSV files with Python
Find image similarity with Python + OpenCV
[Automation with python! ] Part 2: File operation
Create a file uploader with Django
Excel aggregation with Python pandas Part 1
Create and return a CP932 CSV file for Excel with Chalice
Create a Python function decorator with Class
Exclusive control with lock file in Python
Create wordcloud from your tweet with python3
Build a blockchain with Python ① Create a class
Read CSV file with python (Download & parse CSV file)
Create a dummy image with Python + PIL.
Check the existence of the file with python
Draw Nozomi Sasaki in Excel with python
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
Convert Excel data to JSON with python
Let's read the RINEX file with Python ①
Create Python + uWSGI + Nginx environment with Docker
Create a large text file with shellscript
Excel aggregation with Python pandas Part 2 Variadic
[Easy Python] Reading Excel files with openpyxl
Create a word frequency counter with Python 3.4
Create a deb file from a python package
Record with Python → Save file (sounddevice + wave)
[GPS] Create a kml file in Python
[Python] Quickly create an API with Flask
Create an add-in-enabled Excel instance with xlwings
Create an English word app with python
[Easy Python] Reading Excel files with pandas