[Python] Representing the number of complaints from life insurance companies in a bar graph

Overview

――Recently, I got a life insurance policy from an acquaintance. ――But can you really trust the insurance company? ?? I thought, I looked at the number of complaints on this site. ――It's hard to understand because there are many complaints and many insurance companies ... --I tried to express the number of complaints as a bar graph using matplotlib of Python.

Express the number of complaints (cases) in a bar graph

bar graph

――Japan Post Insurance Co., Ltd. has the most complaints! ――But if you are an insurance company with a large number of contracts from the beginning, the number of complaints may also increase. ?? ??

code

from bs4 import BeautifulSoup
import pandas as pd
import re
import matplotlib.pyplot as plt
import requests


url = requests.get("https://www.seiho.or.jp/member/complaint/")
url.raise_for_status()
bs = BeautifulSoup(url.text, "html.parser")


#Express the number of complaints (cases) in a bar graph

#Insurance company name
#Since the name is long, delete "Life Insurance Co., Ltd."
company_name_list = [re.sub('Life insurance company','',i.get_text().replace('\n','') )
                      for i in bs.select('div.headMod04.mt30')]
#Number of complaints (cases)
claim_count_list = [int(((j.get_text())[:-1]).replace(',','')) 
                    for i in bs.select('table.tblMod02.tblP2.mt10') 
                    for j in i.select('td.vaM.taR')]
#Graph creation
plt.title("Number of complaints")  
plt.xlabel('Name of Life Insurance Co., Ltd.')
plt.ylabel('Case')
plt.xticks(rotation=90, fontsize=8)
plt.bar(company_name_list,claim_count_list)
plt.show()

Representing the percentage of complaints in a bar graph

bar graph

--Cardif Life Insurance Co., Ltd. has a high percentage of complaints! ――But since the number of contracts and complaints is small compared to the whole, it is delicate to simply decide as an insurance company with many complaints ... --The ratio of complaints between Japan Post Insurance Co., Ltd. and Lifenet Life Insurance Co., Ltd. is quite large ...

code

from bs4 import BeautifulSoup
import pandas as pd
import re
import matplotlib.pyplot as plt
import requests


url = requests.get("https://www.seiho.or.jp/member/complaint/")
url.raise_for_status()
bs = BeautifulSoup(url.text, "html.parser")

#Representing the percentage of complaints in a bar graph

#Insurance company name
#Since the name is long, delete "Life Insurance Co., Ltd."
company_name_list = [re.sub('Life insurance company','',i.get_text().replace('\n','') )
                      for i in bs.select('div.headMod04.mt30')]
#Number of complaints received by the company (cases)
claim_count_list = [int(((j.get_text())[:-1]).replace(',','')) 
                    for i in bs.select('table.tblMod02.tblP2.mt10') 
                    for j in i.select('td.vaM.taR')]
#Number of individual insurance policies (cases)
guest_number_list = [int((j.get_text())[:-1].replace(',','')) 
                      for i in bs.select('table.tblMod02.tblP2.mt15') 
                      for j in i.select('td.vaM.taR')]
guest_number_list = [guest_number_list[i] for i in range(len(guest_number_list)) if i%2 == 0]

#Complaint rate (%)
claim_rate_list = [(i/j) * 100 for i,j in zip(claim_count_list,guest_number_list)]

plt.title("Complaint rate")  
plt.xlabel('Name of Life Insurance Co., Ltd.')
plt.ylabel('%')
plt.xticks(rotation=90, fontsize=8)
plt.bar(company_name_list,claim_rate_list)
plt.show()
        

Express the breakdown of complaints in a stacked bar graph

bar graph

――The breakdown of complaints looks the same overall

code

from bs4 import BeautifulSoup
import pandas as pd
import re
import matplotlib.pyplot as plt
import requests


url = requests.get("https://www.seiho.or.jp/member/complaint/")
url.raise_for_status()
bs = BeautifulSoup(url.text, "html.parser")


#Express the breakdown of complaints in a stacked bar graph

#Insurance company name
#Since the name is long, delete "Life Insurance Co., Ltd."
company_name_list = [re.sub('Life insurance company','',i.get_text().replace('\n','') )
                      for i in bs.select('div.headMod04.mt30')]
#Contents of the number of items
claim_detail = ['New contract relationship','Storage related','Conservation relations','Insurance money','Other']
#Breakdown of complaints (number of relevant items / number of complaints)
claim_detail_list = [float((j.get_text())[:-1]) 
                      for i in bs.select('table.tblMod02.tblP2.mt10') 
                      for j in i.select('td.taR') 
                      if "%" in j.get_text()]
# claim_detail_Divide the list into 5 contents of the number of items
def list_(num):
    return [claim_detail_list[i] 
            for i in range(len(claim_detail_list)) 
            if i%5==(num - 1)]
#5 different lists
all_list = [list_(1),list_(2),list_(3),list_(4),list_(5)]

dataset = pd.DataFrame(all_list,
                        index=claim_detail,
                        columns=company_name_list)
#Graph creation
fig, ax = plt.subplots(figsize=(10, 8))
for i in range(len(dataset)):
    ax.bar(dataset.columns, dataset.iloc[i], bottom=dataset.iloc[:i].sum())
ax.set(xlabel='Name of Life Insurance Co., Ltd.', ylabel='Breakdown of complaints')
plt.title("Breakdown of complaints")  
plt.xticks(rotation=90, fontsize=12)
ax.legend(dataset.index)
plt.show()

Summary

――I would appreciate it if you could refer to it when choosing life insurance! !! ――But I want you to decide the insurance by actually looking at the HP, not just the graph! (Excuse for escape)

reference

I created a stacked bar graph with matplotlib in Python and added a data label Complaint reception information and insurance payment information of life insurance companies

Recommended Posts

[Python] Representing the number of complaints from life insurance companies in a bar graph
Visualize the number of complaints from life insurance companies
Get the number of specific elements in a python list
Get the number of readers of a treatise on Mendeley in Python
Check the in-memory bytes of a floating point number float in Python
Output the number of CPU cores in Python
Draw a graph of a quadratic function in Python
Get the caller of a function in Python
Make a copy of the list in Python
Find the number of days in a month
Output in the form of a python array
Let's use Python to represent the frequency of binary data contained in a data frame in a single bar graph.
Check if the string is a number in python
[Python] A program that counts the number of valleys
How to get the number of digits in Python
Python points from the perspective of a C programmer
Get the size (number of elements) of UnionFind in Python
A reminder about the implementation of recommendations in Python
A python script that gets the number of jobs for a specified condition from indeed.com
Get the value of a specific key in a list from the dictionary type in the list with Python
[Python] A program that finds the shortest number of steps in a game that crosses clouds
Find out the apparent width of a string in python
Examine the margin of error in the number of deaths from pneumonia
Different from the import type of python. from A import B meaning
Have the equation graph of the linear function drawn in Python
[Note] Import of a file in the parent directory in Python
[Homology] Count the number of holes in data with Python
What beginners learned from the basics of variables in python
Find the eigenvalues of a real symmetric matrix in Python
A library that monitors the life and death of other machines by pinging from Python
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
How to quickly count the frequency of appearance of characters from a character string in Python?
Create an instance of a predefined class from a string in Python
I checked the distribution of the number of video views of "Flag-chan!" [Python] [Graph]
Count the number of Thai and Arabic characters well in Python
How to determine the existence of a selenium element in Python
Save the result of the life game as a gif with python
[Python] Let's reduce the number of elements in the result in set operations
Existence from the viewpoint of Python
Read the standard output of a subprocess line by line in Python
How to check the memory size of a dictionary in Python
[Python] Get the update date of a news article from HTML
A function that measures the processing time of a method in python
Read a file in Python with a relative path from the program
Set up a dummy SMTP server in Python and check the operation of sending from Action Mailer
Count the number of times two values appear in a Python 3 iterator type element at the same time
4 methods to count the number of occurrences of integers in a certain interval (including imos method) [Python implementation]
[Completed version] Try to find out the number of residents in the town from the address list with Python
A story about creating a program that will increase the number of Instagram followers from 0 to 700 in a week
Get a capture of the entire web page in Selenium Python VBA
[Python] A program that calculates the number of chocolate segments that meet the conditions
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
If you want a singleton in python, think of the module as a singleton
Graph of the history of the number of layers of deep learning and the change in accuracy
Get the number of searches with a regular expression. SeleniumBasic VBA Python
[Python] A program that calculates the number of socks to be paired
Generate a list packed with the number of days in the current month.
[Python] How to put any number of standard inputs in a list
[Python] Calculate the number of digits required when filling in 0s [Note]
Test & Debug Tips: Create a file of the specified size in Python
Graph the change in the number of keyword appearances per month using pandas