LoginSignup
8

More than 1 year has passed since last update.

posted at

updated at

渋谷の公衆トイレをクラスタリングしてみた

MYJLab Advent Calendar 2019 24日目の記事です🎄

背景

意味不明な、クリスマス感のない、軽めの記事が書きたかった!🙄

実践

使用したデータセット

渋谷区オープンデータサイトからcsv形式のデータ頂きました。
合計82個の公衆トイレが渋谷にはあるらしいです。意外と多いです。

準備

import pandas as pd
import folium
import numpy as np
from geopy.geocoders import Nominatim
from sklearn.cluster import KMeans

データ取得

綺麗なデータなので、前処理は欠損値の除去のみで済みました!っしゃ

df = pd.read_csv('131130_public_toilet.csv', usecols=[4,9,12,13])
# 欠損値があればその行を消去
df_d = df.dropna(how='any')
df_r = df_d.reset_index(drop=True)
df.head()

スクリーンショット 2019-12-21 17.59.31.png

緯度経度取得


# 渋谷の緯度経度を取得
address = 'Shibuya, Tokyo, Japan'
geolocator = Nominatim(user_agent="foursquare_agent")
location = geolocator.geocode(address)
latitude = location.latitude
longitude = location.longitude
print('緯度:{}, 経度:{}'.format(latitude, longitude))

スクリーンショット 2019-12-21 18.07.13.png

Folium使ってMapに表示


map_shibuya = folium.Map(location=[latitude, longitude], zoom_start=13)

for lat, lng in zip(df_shibuya['緯度'], df_shibuya['経度']):
    folium.CircleMarker(
        [lat, lng],
        radius=5,
        color='red',
        fill=True,
        fill_opacity=0.7,
        parse_html=False).add_to(map_shibuya) 

map_shibuya

スクリーンショット 2019-12-21 18.44.43.png

k-means法でクラスタリング

クラスタ数は3個に設定しました。

# Numpyの行列に変換
cust_array = np.array([df_shibuya['緯度'].tolist(),
                       df_shibuya['経度'].tolist()])
# 行列を転置
cust_array = cust_array.T

kclusters = 3
# K-means実行
pred = KMeans(n_clusters=kclusters).fit_predict(cust_array)
pred

スクリーンショット 2019-12-21 20.40.08.png

0〜2の3つのクラスタ番号が振られてると思います。
これをデータフレームのカラムに追加します。

# データフレームにクラスタ番号を追加
df_shibuya['cluster_id'] = pred
df_shibuya.head()

スクリーンショット 2019-12-21 20.48.20.png

クラスタリングの結果を視覚化

3つのクリスマスカラーで装飾します。

# クラスタ番号ごとに色を設定
colors_array = ['red','brown','green']

# add markers to the map
for lat, lon, cluster in zip(df_shibuya['緯度'], df_shibuya['経度'], df_shibuya['cluster_id']):
    folium.CircleMarker(
        [lat, lon],
        radius=5,
        popup=cluster,
        color=colors_array[cluster-1],
        fill=True,
        fill_color=colors_array[cluster-1],
        fill_opacity=0.7).add_to(map_shibuya)

map_shibuya

スクリーンショット 2019-12-21 21.19.53.png

以上、無意味なクラスタ分析でした!

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
What you can do with signing up
8