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-19

はじめに

今回は、前回作った市区町村リストを使用して、
住所データから都道府県・市区町村を抽出してみます

環境

~ % python -V
Python 3.11.9

~ % pip list | grep pandas
pandas             2.2.3

準備

市区町村マスタ

以下内容のCSVデータを用意します(前回記事参照

69dde5fb12574bc8f52d-2.png

抽出対象の住所リスト

ChatGPTで適当に作成します

address.csv
東京都渋谷区代々木2丁目2-1
北海道札幌市厚別区厚別中央2条5丁目
大阪府豊中市新千里東町1丁目5-3
京都府綾部市駅前通り1丁目9
神奈川県鎌倉市小町1丁目9-3
愛知県知立市中町中132
兵庫県芦屋市船戸町1-31
福岡県糸島市前原中央1丁目1-1
宮城県加美郡加美町字南町115-1
広島県安芸郡熊野町出来庭2丁目1-1
茨城県稲敷郡阿見町中央1丁目1-1
静岡県賀茂郡南伊豆町下賀茂413-1
千葉県安房郡鋸南町吉浜516
新潟県南魚沼郡湯沢町大字湯沢2497
岐阜県大野郡白川村荻町1086
長野県木曽郡木祖村薮原1191
群馬県多野郡上野村大字勝山127
岡山県久米郡美咲町原田2155
栃木県下都賀郡壬生町壬生乙2452
熊本県球磨郡水上村大字湯山1322-1

プログラム

import pandas as pd
import re
pd.set_option('display.unicode.east_asian_width', True)

# 都道府県名の抽出パターン
pref_pattern = r'(東京都|北海道|(?:京都|大阪)府|.{2,3}県)'

# 市区町村マスタの読み込み
# 市区町村名を結合したカラムを作っておく city_ward
city_df = pd.read_csv('city_list.csv')
city_df = city_df.fillna('')
# 市・区・町・村・郡の並びはクセがあるので調整の必要あり
# 今回は 区(ward)/郡(county)/市区町村(city) と想定し、
# 連結して一度に抽出するが、それぞれ抽出する方が良いかも
city_df['city_name'] = city_df.apply(lambda x: f"{x['ward']}{x['county']}{x['city']}", axis=1)

# 市区町村名のリストを名の長い順にソートし、抽出パターンに
city_pattern = '|'.join(sorted(city_df['city_name'].tolist(), key=len, reverse=True))

# 住所データの読み込み
df = pd.read_csv('address.csv', header=None, names=['address'])

def extract(address):
    # 都道府県名を抽出
    pref_match = re.match(pref_pattern, address)
    pref = pref_match.group() if pref_match else None
    rest = address[len(pref):] if pref else address # 都道府県名を除いた残り文字列

    # 市区町村名を抽出
    city_match = re.match(city_pattern, rest)
    city = city_match.group() if city_match else None
    return pd.Series([pref, city])

# 抽出結果を新しいカラムに追加
df[['pref', 'city']] = df['address'].apply(extract)

結果

7ce41fb74f1f70305426.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?