人口移動が多いのは何月？ e-Stat API機能 で取得したデータをプロットする


# 人口移動が多いのは何月？ e-Stat API機能 で取得したデータをプロットする


```python
import os
import io
import requests
import pandas as pd
import seaborn as sns

%matplotlib inline
```

## 統計調査名を取得
https://www.e-stat.go.jp/api/api-info/api-data


```python
url = "http://api.e-stat.go.jp/rest/3.0/app/getSimpleStatsList"
app_id = os.getenv("E_STAT_API_APP_ID")
params = {"appId": app_id, "statsNameList": "Y"}
```


```python
response = requests.get(url, params=params)
```


```python
csv_text = response.text[response.text.find('"TABLE_INF",') :]
```


```python
df = pd.read_csv(io.StringIO(csv_text), dtype="object")
```


```python
df[df.STAT_NAME.str.contains("人口")]
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>TABLE_INF</th>
      <th>STAT_CODE</th>
      <th>STAT_NAME</th>
      <th>GOV_ORG_CODE</th>
      <th>GOV_ORG_NAME</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>14</th>
      <td>00200502</td>
      <td>00200502</td>
      <td>社会・人口統計体系</td>
      <td>00200</td>
      <td>総務省</td>
    </tr>
    <tr>
      <th>17</th>
      <td>00200523</td>
      <td>00200523</td>
      <td>住民基本台帳人口移動報告</td>
      <td>00200</td>
      <td>総務省</td>
    </tr>
    <tr>
      <th>18</th>
      <td>00200524</td>
      <td>00200524</td>
      <td>人口推計</td>
      <td>00200</td>
      <td>総務省</td>
    </tr>
    <tr>
      <th>76</th>
      <td>00450011</td>
      <td>00450011</td>
      <td>人口動態調査</td>
      <td>00450</td>
      <td>厚生労働省</td>
    </tr>
  </tbody>
</table>
</div>




```python
df[df.STAT_NAME.str.contains('人口')].iloc[1]
```




    TABLE_INF           00200523
    STAT_CODE           00200523
    STAT_NAME       住民基本台帳人口移動報告
    GOV_ORG_CODE           00200
    GOV_ORG_NAME             総務省
    Name: 17, dtype: object




```python
table_inf = df[df.STAT_NAME.str.contains('人口')].iloc[1].TABLE_INF
```

## 統計表情報取得
https://www.e-stat.go.jp/api/api-info/e-stat-manual3-0#api_2_1


```python
url = "http://api.e-stat.go.jp/rest/3.0/app/getSimpleStatsList"
app_id = os.getenv("E_STAT_API_APP_ID")
params = {"appId": app_id, "statsCode": table_inf}
```


```python
response = requests.get(url, params=params)
```


```python
csv_text = response.text[response.text.find('"TABLE_INF",') :]
```


```python
df = pd.read_csv(io.StringIO(csv_text), dtype="object")
```


```python
table_inf = df[(df.CYCLE == "月次") & (df.TABLE_CATEGORY == "2010年1月～")].iloc[0].TABLE_INF
```

## メタ情報取得
https://www.e-stat.go.jp/api/api-info/e-stat-manual3-0#api_2_2


```python
url = "http://api.e-stat.go.jp/rest/3.0/app/getSimpleMetaInfo"
params = {"appId": app_id, 'statsDataId':table_inf}
```


```python
response = requests.get(url, params=params)
```


```python
csv_text = response.text[response.text.find('"CLASS_OBJ_ID",') :]
```


```python
df = pd.read_csv(io.StringIO(csv_text), dtype="object")
```


```python
df.drop_duplicates('CLASS_OBJ_ID')
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>CLASS_OBJ_ID</th>
      <th>CLASS_OBJ_NAME</th>
      <th>CLASS_CODE</th>
      <th>CLASS_NAME</th>
      <th>CLASS_LEVEL</th>
      <th>CLASS_UNIT</th>
      <th>CLASS_PARENT_CODE</th>
      <th>CLASS_ADD_INF</th>
      <th>CLASS_EXPLANATION</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>tab</td>
      <td>表章項目</td>
      <td>06</td>
      <td>他都道府県からの転入者数</td>
      <td>NaN</td>
      <td>人</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
    </tr>
    <tr>
      <th>1</th>
      <td>cat01</td>
      <td>性別</td>
      <td>0</td>
      <td>総数</td>
      <td>1</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
    </tr>
    <tr>
      <th>4</th>
      <td>cat02</td>
      <td>年齢（５歳階級）</td>
      <td>000</td>
      <td>総数</td>
      <td>1</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
    </tr>
    <tr>
      <th>24</th>
      <td>area</td>
      <td>全国・都道府県</td>
      <td>00000</td>
      <td>全国</td>
      <td>1</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
    </tr>
    <tr>
      <th>72</th>
      <td>time</td>
      <td>時間軸（月次）</td>
      <td>2018001212</td>
      <td>2018年12月</td>
      <td>2</td>
      <td>NaN</td>
      <td>2018000000</td>
      <td>NaN</td>
      <td>NaN</td>
    </tr>
  </tbody>
</table>
</div>



## 統計データ取得
https://www.e-stat.go.jp/api/api-info/e-stat-manual3-0#api_2_3


```python
url = "http://api.e-stat.go.jp/rest/3.0/app/getSimpleStatsData"
params = {
    "appId": app_id,
    "statsDataId": table_inf,
    "cdArea": "00000",
    "cdCat01": "0",
    "cdCat02": "000",
}
```


```python
response = requests.get(url, params=params)
```


```python
csv_text = response.text[response.text.find('"tab_code",') :]
```


```python
df = pd.read_csv(io.StringIO(csv_text), dtype="object")
```

## プロット


```python
df.pipe(
    lambda df: df.assign(year_month=pd.to_datetime(df["時間軸（月次）"], format="%Y年%m月"))
).pipe(
    lambda df: df[["year_month", "value"]]
    .astype({"value": int})
    .set_index("year_month")
    .sort_index()
).plot(
    figsize=(12, 3)
)
pass
```


![output_28_0.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/473192/d332c7e7-4a19-697a-188b-2d3d36b56c14.png)



```python
(
    df.pipe(
        lambda df: df.assign(year_month=pd.to_datetime(df["時間軸（月次）"], format="%Y年%m月"))
    )
    .pipe(
        lambda df: df[["year_month", "value"]]
        .astype({"value": int})
        .set_index("year_month")
        .sort_index()
    )
    .pipe(lambda df: df.assign(month=df.index.month))
    .groupby("month")
    .mean()
).plot.bar(rot=0)
pass
```


![output_29_0.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/473192/399e261f-4ff8-f757-1789-6090bdd46b4c.png)



```python
df_sns = (
    df.pipe(
        lambda df: df.assign(year_month=pd.to_datetime(df["時間軸（月次）"], format="%Y年%m月"))
    )
    .pipe(
        lambda df: df[["year_month", "value"]]
        .astype({"value": int})
        .set_index("year_month")
        .sort_index()
    )
    .pipe(lambda df: df.assign(month=df.index.month))
)
```


```python
sns.catplot(x="month", y="value", data=df_sns)
pass
```


![output_31_0.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/473192/d2917513-434d-8895-ed4a-8072863d23c3.png)


```python
sns.violinplot(x="month", y="value", data=df_sns)
pass
```


![output_32_0.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/473192/67b3b152-e7be-1b95-c873-3627e9f24eaf.png)



```python
sns.boxplot(x="month", y="value", data=df_sns)
pass
```


![output_33_0.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/473192/52e27473-9379-0401-8147-a9ed856da181.png)