File size: 1,089 Bytes
a4b2e63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import pandas as pd
import datetime


def get_household_survey():
    # e-Statにユーザー登録し、APIキーを取得しておくこと
    # URL: https://www.e-stat.go.jp/api/
    API_KEY = "ddc1349cf530bdee69ca6a7ad6c0e2301aeb0780"

    # 取得年月の設定
    latest_year = int(datetime.datetime.now().strftime('%Y'))
    year_period = 5
    years = list(range(latest_year, latest_year - year_period, -1))
    months = range(1, 13)
    periods = []
    for y in years:
        y = y * 1_000_000
        for m in months:
            ym = y + m * 100 + m
            periods.append(str(ym))
    periods = ("%2C").join(periods)

    # データ取得
    url = f"http://api.e-stat.go.jp/rest/3.0/app/getSimpleStatsData?cdTab=01&cdCat02=03&cdArea=00000&cdTime={periods}&appId={API_KEY}&lang=J&statsDataId=0003343671&metaGetFlg=Y&cntGetFlg=N&explanationGetFlg=Y&annotationGetFlg=Y&sectionHeaderFlg=1&replaceSpChars=0"
    df = pd.read_csv(url, header=28)
    return df


if __name__ == "__main__":
    df = get_household_survey()
    df.to_csv("household_survey.csv", index=False)