0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

市区町村コード一覧を作成する

Last updated at Posted at 2025-04-13

はじめに

オープンデータを利用して市区町村コードの一覧を作成してみます

データソース

デジタル庁 レジストリカタログ
日本 市区町村マスター データセット

他に使えそうなソース

総務省
https://www.soumu.go.jp/denshijiti/code.html

  • 郡名なし
  • 政令指定都市の区名なし

日本郵便
https://www.post.japanpost.jp/zipcode/download.html

  • 北方領土含まない
  • 更新頻度は高い

環境

~ % python -V
Python 3.11.9

~ % pip list | grep pandas
pandas             2.2.3

一覧作成

import pandas as pd

# 公開データの読み込み
df = pd.read_csv('mt_city_all.csv', dtype={'lg_code':str}, usecols=['lg_code','pref','city','ward'])
# カラム名を調整(市区町村コードのカラムを"code"に変更
df.rename(columns={'lg_code': 'code'}, inplace=True)

# CSV作成だけなら不要ではあるが
df = df.fillna('') # 区名のない部分を補完
df.set_index('lg_code', inplace=True) # 市区町村コードをindexに

# CSV出力
df.to_csv('city_list.csv') # 市区町村コードをindexにしたので、そのまま出力

結果

69dde5fb12574bc8f52d.png

郡名も追加

import os, sys
import re

import pandas as pd

df = pd.read_csv('mt_city_all.csv', dtype={'lg_code':str}, usecols=['lg_code','county','pref','city','ward'])
df.rename(columns={'lg_code': 'code'}, inplace=True)
df.reindex(columns=['lg_code','pref','county','city','ward'])
df = df.fillna('')
df.set_index('code', inplace=True)
df.to_csv('city_list.csv')

69dde5fb12574bc8f52d-2.png
※一部抜粋

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?