LoginSignup
5
6

More than 5 years have passed since last update.

気象庁のデータを取得して、pandasでデータを整形してみる。

Last updated at Posted at 2017-10-23

気象庁のデータをBeautifulSoupを用いてパースし、pandasを用いてデータを整形する。

必要なライブラリなどをインポートします。

import urllib.request
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import pandas as pd
from pandas import DataFrame
from bs4 import BeautifulSoup

データを読み出すための関数を定義します。
この関数は年と月を指定して、その時のデータを読み出します。

def read_data(month, year):
    html = urllib.request.urlopen("http://www.data.jma.go.jp/obd/stats/etrn/view/daily_s1.php?prec_no=44&block_no=47662&year="+str(year)+"&month="+str(month)+"&day=&view=")
    data = BeautifulSoup(html, 'lxml')

    data.prettify()
    title = data.find("h3")
    day = data.find_all(class_="data_0_0")

    y_vals = []

    for i, item in enumerate(day):
        if i % 20 == 5: 
            y_vals.append(float(item.string))

    ave_data = sum(y_vals) / len(y_vals)
    return ave_data

以下のようにして、先ほど定義した関数を用いてデータを読み出し、
pandasのDataFrameを利用して、データを整形します。
DataFrameに配列を渡す時に、indexとcolumnsを指定することで、インデックスとコラムを指定することができます。
ここで2014年の読み出しを飛ばしていますが、これは2014年のデータのみに均質でない値が存在し、関数により読み出すことができず、別処理を加えなければいけないためです。

気象庁

x_ave = np.zeros((10, 12))

year = 2006
for i in range(0, 10):
    if year + i == 2014:
        year = year + 1
    for month in range(0,12):
        x_ave[i][month] = (read_data(month + 1, year + i))

index = ['2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2015', '2016']
columns = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']

temperature_ave = DataFrame(x_ave, index=index, columns=columns)
temperature_ave = temperature_ave.round(1)
print(temperature_ave)
#   
          1   2    3       4       5       6       7       8       9      10      11     12
2006    5.1 6.7  9.8    13.6    19.0    22.5    25.6    27.5    23.5    19.5    14.4    9.5
2007    7.6 8.6 10.8    13.7    19.8    23.2    24.4    29.0    25.2    19.0    10.3    6.0
2008    5.9 5.5 10.7    14.7    18.5    20.9    27.0    26.8    24.4    19.4    13.1    9.8
2009    6.8 7.8 10.0    15.7    20.1    22.5    26.3    26.6    23.0    19.0    13.4    9.0
2010    7.0 6.5  9.1    12.4    19.0    23.6    28.0    29.6    25.1    18.9    13.5    9.9
2011    5.1 7.0  8.1    14.5    18.5    22.8    27.3    27.5    25.1    19.5    14.9    7.5
2012    4.8 5.4  8.8    14.5    19.6    21.4    26.4    29.1    26.2    19.4    12.7    7.3
2013    5.5 6.2 12.1    15.2    19.8    22.9    27.3    29.2    25.2    19.8    13.5    8.3
2015    5.8 5.7 10.3    14.5    21.1    22.1    26.2    26.7    22.6    18.4    13.9    9.3
2016    6.1 7.2 10.1    15.4    20.2    22.4    25.4    27.1    24.4    18.7    11.4    8.9
5
6
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
5
6