最近東京あついから、ここ数年の気温見た

最近あつい。で、結局ここ最近でどんくらい暑いんだっけか。

ということで、気温データを過去4年分見た

参考にしたのは以下。ありがたや。<br>[https://qiita.com/data-man/items/66f5fa8a7cacc529071c](https://qiita.com/data-man/items/66f5fa8a7cacc529071)

# データ取得

スクレピング。サイトに迷惑にならないように。

<pre><code class="language-python">
pip install requests beautifulsoup4 pandas

import requests
from bs4 import BeautifulSoup
import csv
from datetime import datetime

place_codeA = [44, 46, 43, 82, 91, 14, 62, 52, 34]
place_codeB = [47662, 47670, 47626, 47807, 47936, 47412, 47772, 47590]
place_name = ["東京", "横浜", "熊谷", "福岡", "沖縄", "札幌", "大阪", "仙台"]

base_url = "http://www.data.jma.go.jp/obd/stats/etrn/view/daily_s1.php?prec_no=%s&block_no=%s&year=%s&month=%s&day=1&view=p1"

def str2float(str):
    try:
        return float(str)
    except:
        return 0.0

if __name__ == "__main__":
    current_year = datetime.now().year
    current_month = datetime.now().month
    for place in place_name:
        All_list = [['年月日', '降水量', '気温_平均', '気温_最高', '気温_最低', '湿度_平均', '湿度_最小', '日照時間']]
        print(place)
        index = place_name.index(place)
        for year in range(2020, current_year + 1):
            print(year)
            end_month = 13 if year != current_year else current_month + 1
            for month in range(1, end_month):
                r = requests.get(base_url%(place_codeA[index], place_codeB[index], year, month))
                r.encoding = r.apparent_encoding
                soup = BeautifulSoup(r.text)
                rows = soup.findAll('tr',class_='mtx')
                rows = rows[4:]
                for row in rows:
                    data = row.findAll('td')
                    rowData = []
                    rowData.append(str(year) + "/" + str(month).zfill(2) + "/" + str(data[0].string).zfill(2))
                    rowData.append(str2float(data[3].string))
                    rowData.append(str2float(data[6].string))
                    rowData.append(str2float(data[7].string))
                    rowData.append(str2float(data[8].string))
                    rowData.append(str2float(data[9].string))
                    rowData.append(str2float(data[10].string))
                    rowData.append(str2float(data[16].string))
                    All_list.append(rowData)
        with open(place + '.csv', 'w',encoding="utf_8_sig") as file:
            writer = csv.writer(file, lineterminator='\n')
            writer.writerows(All_list)


</code></pre>

------------------

# データ確認

<pre><code class="language-python">
import pandas as pd

# 都市名のリスト
place_name = ["東京", "横浜", "熊谷", "福岡", "沖縄", "札幌", "大阪", "仙台"]

# 各都市のデータを読み込み、一つのデータフレームに結合
df_all = pd.concat([pd.read_csv(f'{city}.csv').assign(都市=city) for city in place_name])

# 結果を表示
print(df_all.head())
</code></pre>

![](https://pbs.twimg.com/media/F1Z3mTnWYAYCA2j?format=png&name=small)


------------------

# csvにする練習

df_all 使えばいいんだけど。ちょっと練習、ごめんなさいね

<pre><code class="language-python">
place_name_jp = ["東京", "横浜", "熊谷", "福岡", "沖縄", "札幌", "大阪",  "仙台"]
place_name_en = ["Tokyo", "Yokohama", "Kumagaya", "Fukuoka", "Okinawa", "Sapporo", "Osaka", "Nagoya", "Sendai"]
place_dict = dict(zip(place_name_jp, place_name_en))

# 各都市のデータを読み込み、一つのDataFrameに結合
df_list = []
for place_jp, place_en in place_dict.items():
    df = pd.read_csv(f'{place_jp}.csv')
    df['City'] = place_en
    df_list.append(df)

combined_df = pd.concat(df_list)

# 結果をCSVファイルに保存
combined_df.to_csv('combined_data.csv', index=False)
</code></pre>

------------------

# 年間データ

そのまま適当にグラフへ。0データを消し忘れた

<pre><code class="language-python">
import matplotlib.pyplot as plt

# 都市名と英語名の対応
place_name = ["東京", "横浜", "熊谷", "福岡", "沖縄", "札幌", "大阪", "仙台"]
place_name_english = ["Tokyo", "Yokohama", "Kumagaya", "Fukuoka", "Okinawa", "Sapporo", "Osaka", "Nagoya", "Sendai"]

# サブプロットの行と列の数を設定
nrows = 3
ncols = 3

# サブプロットのレイアウトを定義
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(15, 10))

for i, city in enumerate(place_name):
    df = pd.read_csv(f'{city}.csv')
    df['年月日'] = pd.to_datetime(df['年月日'])
    df.set_index('年月日', inplace=True)
    for year in df.index.year.unique():
        df_year = df[df.index.year == year].copy()  # データフレームのコピーを作成
        df_year['Day of Year'] = df_year.index.dayofyear
        df_year.plot(x='Day of Year', y='気温_平均', ax=axes[i//ncols, i%ncols], label=year)
    axes[i//ncols, i%ncols].set_title(place_name_english[i])
    axes[i//ncols, i%ncols].set_xlabel('Day of Year')
    axes[i//ncols, i%ncols].set_ylabel('Average Temperature')
    axes[i//ncols, i%ncols].legend()

plt.tight_layout()
plt.show()

</code></pre>

![](https://pbs.twimg.com/media/F1Z6LUEXsAAUVRg?format=jpg&name=small)



------------------

# 7月データ

そのまま適当にグラフへ。0データをまだ消してない

<pre><code class="language-python">
import matplotlib.pyplot as plt
import pandas as pd

# 都市名と英語名の対応
place_name = ["東京", "横浜", "熊谷", "福岡", "沖縄", "札幌", "大阪"]
place_name_english = ["Tokyo", "Yokohama", "Kumagaya", "Fukuoka", "Okinawa", "Sapporo", "Osaka"]

# サブプロットの行と列の数を設定
nrows = 2
ncols = 4

# サブプロットのレイアウトを定義
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(15, 10))

for i, city in enumerate(place_name):
    df = pd.read_csv(f'{city}.csv')
    df['年月日'] = pd.to_datetime(df['年月日'])
    df.set_index('年月日', inplace=True)
    df = df[df.index.month == 7]  # 7月のデータだけを抽出
    for year in df.index.year.unique():
        df_year = df[df.index.year == year].copy()  # データフレームのコピーを作成
        df_year['Day of Month'] = df_year.index.day
        df_year.plot(x='Day of Month', y='気温_平均', ax=axes[i//ncols, i%ncols], label=year)
    axes[i//ncols, i%ncols].set_title(place_name_english[i])
    axes[i//ncols, i%ncols].set_xlabel('Day of July')
    axes[i//ncols, i%ncols].set_ylabel('Average Temperature')
    axes[i//ncols, i%ncols].legend()

plt.tight_layout()
plt.show()

</code></pre>

![](https://pbs.twimg.com/media/F1Z6XjwXoAkplV8?format=jpg&name=small)

----------------

# 7月データ (0除外)

<pre><code class="language-python">
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# 都市名と英語名の対応
place_name = ["東京", "横浜", "熊谷", "福岡", "沖縄", "札幌", "大阪"]
place_name_english = ["Tokyo", "Yokohama", "Kumagaya", "Fukuoka", "Okinawa", "Sapporo", "Osaka"]

# サブプロットの行と列の数を設定
nrows = 3
ncols = 3

# サブプロットのレイアウトを定義
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(15, 10))

for i, city in enumerate(place_name):
    df = pd.read_csv(f'{city}.csv')
    df['年月日'] = pd.to_datetime(df['年月日'])
    df.set_index('年月日', inplace=True)
    df = df[df.index.month == 7]  # 7月のデータだけを抽出
    df = df[df['気温_最高'] != 0]  # 最高気温が0のデータを除外
    for year in df.index.year.unique():
        df_year = df[df.index.year == year].copy()  # データフレームのコピーを作成
        df_year['Day of Month'] = df_year.index.day
        df_year.plot(x='Day of Month', y='気温_最高', ax=axes[i//ncols, i%ncols], label=year)
    axes[i//ncols, i%ncols].set_title(place_name_english[i])
    axes[i//ncols, i%ncols].set_xlabel('Day of July')
    axes[i//ncols, i%ncols].set_ylabel('Highest Temperature')
    axes[i//ncols, i%ncols].legend()

plt.tight_layout()
plt.show()

</code></pre>

![](https://pbs.twimg.com/media/F1Z69FYXwAACCxL?format=jpg&name=small)

数年を見ても、ここ数日の東京、横浜は暑いことは分かった


----------------

# 6月、7月データ (0除外)

<pre><code class="language-python">
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# 都市名と英語名の対応
place_name = ["東京", "横浜", "熊谷", "福岡", "沖縄", "札幌", "大阪"]
place_name_english = ["Tokyo", "Yokohama", "Kumagaya", "Fukuoka", "Okinawa", "Sapporo", "Osaka"]

# サブプロットの行と列の数を設定
nrows = 2
ncols = 4

# サブプロットのレイアウトを定義
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(15, 10))

for i, city in enumerate(place_name):
    df = pd.read_csv(f'{city}.csv')
    df['年月日'] = pd.to_datetime(df['年月日'])
    df.set_index('年月日', inplace=True)
    df = df[(df.index.month == 6) | (df.index.month == 7)]  # 6月と7月のデータだけを抽出
    df = df[df['気温_最高'] != 0]  # 最高気温が0のデータを除外
    for year in df.index.year.unique():
        df_year = df[df.index.year == year].copy()  # データフレームのコピーを作成
        df_year['Day of Year'] = df_year.index.dayofyear
        df_year.plot(x='Day of Year', y='気温_最高', ax=axes[i//ncols, i%ncols], label=year)
    axes[i//ncols, i%ncols].set_title(place_name_english[i])
    axes[i//ncols, i%ncols].set_xlabel('Date (6/1 - 7/31)')
    axes[i//ncols, i%ncols].set_ylabel('Highest Temperature')
    axes[i//ncols, i%ncols].legend()

plt.tight_layout()
plt.show()

</code></pre>

![](https://pbs.twimg.com/media/F1Z7RNVWYAYnRzP?format=jpg&name=small)

数年を見ても、ここ数日の東京、横浜は暑いことは分かった


----------------

# 6月、7月気温ヒートマップ

<pre><code class="language-python">
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

# 都市名と英語名の対応
place_name = ["東京", "横浜", "熊谷", "福岡", "沖縄", "札幌", "大阪"]
place_name_english = ["Tokyo", "Yokohama", "Kumagaya", "Fukuoka", "Okinawa", "Sapporo", "Osaka"]

for i, city in enumerate(place_name):
    df = pd.read_csv(f'{city}.csv')
    df['年月日'] = pd.to_datetime(df['年月日'])
    df.set_index('年月日', inplace=True)
    df = df[(df.index.month == 6) | (df.index.month == 7)]  # 6月と7月のデータだけを抽出
    df = df[df['気温_最高'] != 0]  # 最高気温が0のデータを除外
    df['Day of Year'] = df.index.dayofyear
    df['Year'] = df.index.year
    df_pivot = df.pivot(index='Year', columns='Day of Year', values='気温_最高')
    
    # df_pivotが空でないことを確認
    if not df_pivot.empty:
        plt.figure(figsize=(10, 8))
        sns.heatmap(df_pivot, cmap='coolwarm', cbar_kws={'label': 'Highest Temperature'})
        plt.title(place_name_english[i])
        plt.xlabel('Date (6/1 - 7/31)')
        plt.ylabel('Year')
        plt.show()
    else:
        print(f"No data available for {city}. Skipping...")

</code></pre>

![](https://pbs.twimg.com/media/F1Z7wKtXsAAo-RN?format=png&name=900x900)
![](https://pbs.twimg.com/media/F1Z7zMCXwAIqDiC?format=png&name=900x900)
![](https://pbs.twimg.com/media/F1Z8Gk6XsAAx7AA?format=png&name=900x900)
![](https://pbs.twimg.com/media/F1Z8JAvWAAQoS9k?format=png&name=900x900)
![](https://pbs.twimg.com/media/F1Z8N22WYAEuFZj?format=png&name=900x900)
![](https://pbs.twimg.com/media/F1Z8P4BXgAMFWt-?format=png&name=900x900)

X軸の表示、変えてなかった、見づらい。失礼

また今度