Published Date : 2020年9月27日2:49

【python】賃金階級年齢階級別労働者割合の算出
【python】Calculation of the ratio of workers by wage class and age group


This blog has an English translation


YouTubeにアップした動画、「【python】賃金階級年齢階級別労働者割合の算出」の補足説明の記事です。

Here's a little more about the 「【python】Calculation of the ratio of workers by wage class and age group」 video I uploaded to YouTube.


目次

Table of Contents




① 動画の説明
① Video Description



まずは厚生労働省が公表している[平成30年賃金構造基本統計調査の概況]のサイトへ行きます。

First, go to the website of [Overview of the 2018 Basic Survey on Wage Structure] published by the Ministry of Health, Labour and Welfare.

このPDFをダウンロードして、PythonからPDFを読めるように、[pdfminer.six]をインストールします。

Download this PDF and install [pdfminer.six] so you can read it from Python.

pip install pdfminer.six

[pdfminer.six]は日本語にも対応しています。

[pdfminer.six] reads PDFs even if they are written in Japanese.

[pdfminer.six]は一度インストールされれば、コマンドラインからも利用できます。

Once installed, [pdfminer.six] is also available from the command line.

python pdf2txt.py samples/simple1.pdf

ですが、パスが長くなると、コマンドが見にくく、そして入力しにくくなるので、

However, the longer the path, the harder it is to see and type commands,

Pythonファイルから[pdfminer.six]を動かせるようにします。

so let [pdfminer.six] run from a Python file.

sysモジュールとpathlibモジュールで[pdfminer.six]の実行ファイルである[pdf2txt.py]までのPathを取得します。

Use the sys and pathlib modules to get the path up to the pdf2txt.py, which is the pdfminer.six executable.

その後subprocessのcallを使用して、コマンドラインで引数付きでPythonファイルを実行するようにします。

Then use call in subprocess to run the Python file with arguments on the command line.

import sys
from pathlib import Path
from subprocess import call

pdf_path = r"C:\Users\user\Downloads\13.pdf"

pdf2txt_py_path = Path(sys.exec_prefix) / "Scripts" / "pdf2txt.py"

call(["py", str(pdf2txt_py_path), "-o extract-pdf.txt", pdf_path])

このPythonファイルを保存して、実行します。

Save and run this Python file.

python run_p2t.py

するとこのように、綺麗にPDFから文字が抜き出されます。

This will pull the text out of the PDF beautifully.

PDFから抜き出した表の文字は少し並びがおかしい箇所がありますが、きちんと抽出されています。

The characters in the table extracted from the PDF are properly extracted, although there are some strange parts.

この[pdfminer.six]でPDFから文字を抜き出したテキストファイルから、

Use the information in the [Table 7 Ratios of Workers by Wage, Sex and Age Group (2 -2)]

[第7表賃金階級、性、年齢階級別労働者割合(2-2)]の表の情報を使いましょう。

table from a text file extracted from a PDF using the [pdfminer.six].

この表の情報を整理して、別のテキストファイルとして保存しましょう。

Organize the information in this table and save it as a separate text file.

それをCSVファイルとして保存しておきます。

Save it as a CSV file.

import pandas as pd

text_file_path = r"C:\Users\user\第7表2-2.txt"
df = pd.read_csv(text_file_path)
csv_file_path = r"C:\Users\user\第7表2-2.csv"
df.to_csv(csv_file_path, index=None)

これだけだとあまり面白くないので、

I don't think this is all that interesting,

このCSVファイルとPandasを使って、ユーザーが年齢と年収を入力すると、

so I'll use this CSV file and Pandas to input your age

そのユーザーの年収はそのユーザーと同じ年代の中で、

and annual income and create a program that

どの程度の割合存在するのかを教えてくれるプログラムを作成します。

shows what percentage of your age group is getting the same salary as you.

いつも通りPandasを使って、データを処理していきます。

We use Pandas as usual to process the data.

import pandas as pd
import re

df = pd.read_csv(csv_file_path)

range_ai = df['賃金階級'][:24].apply(
    lambda x: x.replace('(千円)', '').split('~'))
range_ai = range_ai.apply(
    lambda x: [float(y) if y != '' else '' for y in x])

range_age = pd.Series([age.replace('歳', '').split('~')
                        for age in df.columns[2:]])
range_age = range_age.apply(
    lambda x: [int(y) if y != '' else '' for y in x])

後はユーザーの年齢と年収が表のどの箇所に該当するかを見つけ出し、

All you have to do is find out where the user's age and annual income

Print関数を使って、最終的な答えを表示させるようにするだけです。

fall in the table and use the Print function to display the final result.

# Please enter your annual income(ten thousand yen)
annual_income = input('あなたの年収を入力してください(万円) : ')
# Please enter your age
age = input('あなたの年齢を入力してください : ')

ai_index = 0
for idx, l_ in enumerate(range_ai):
    if idx == 0:
        l = [i for i in range(0, int(l_[1]+0.1))]
    elif idx == len(range_ai)-1:
        l = [i for i in range(int(l_[0]), 30000)]
    else:
        l = [i for i in range(int(l_[0]), int(l_[1]+0.1))]

    if int(annual_income) in l:
        ai_index = idx

age_index = 0
for idx, l_ in enumerate(range_age):
    if idx == 0:
        l = [19]
    elif idx == len(range_age)-1:
        l = [i for i in range(70, 120)]
    else:
        l = [i for i in range(int(l_[0]), int(l_[1])+1)]

    if int(age) in l:
        age_index = idx

answer = df.iat[ai_index, age_index + 2]
# The annual income of {annual_income} (ten thousand yen) at your age of {age} is {answer}% of {df.columns[age_index+2]} years old.
print(f'\nあなたの年齢({age}才)で、年収({annual_income})万円は、({df.columns[age_index+2]})の中では{answer}%の割合です。')

Django等のウェブフレームワークを使ってこのプログラムをウェブ上で使えるようにしたら面白いかもしれません。

It might be interesting to make this program available on the web using a web framework like Django.



以上です。お疲れ様です。

That's all. Thank you for your hard work.