# 【conda env: geo】
# 数値演算、描画用ライブラリ読み込み
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import japanize_matplotlib
import seaborn as sns
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
# 生データ(男子高校生100人の体重)
weight = np.array([43.6, 45.2, 45.4, 45.8, 47.2, 47.8, 48.2, 48.7, 48.8, 48.9, 49.0, 49.0, 49.4,
49.5, 49.8, 50.4, 50.5, 50.9, 50.9, 51.2, 51.2, 51.2, 51.3, 51.3, 51.6, 51.7,
51.7, 51.8, 52.0, 52.0, 52.1, 52.1, 52.1, 52.2, 52.3, 52.7, 52.7, 52.8, 52.9,
52.9, 53.1, 53.1, 53.8, 54.0, 54.5, 54.5, 54.6, 54.7, 54.7, 54.7, 54.8, 54.9,
55.1, 55.1, 55.2, 55.3, 55.4, 55.4, 55.4, 55.6, 55.7, 55.8, 55.9, 56.1, 56.3,
56.3, 56.3, 56.4, 56.5, 56.7, 56.8, 57.0, 57.1, 57.1, 57.2, 57.3, 57.6, 57.7,
57.8, 58.1, 58.4, 58.6, 58.7, 58.7, 58.7, 58.7, 59.1, 59.3, 59.9, 60.0, 60.1,
60.3, 60.5, 60.6, 60.6, 60.7, 61.3, 62.7, 64.2, 64.6])
# 度数分布表の作成
bins = np.arange(43,66,2)
dosu, cls = np.histogram(weight, bins)
cum_dosu = np.cumsum(dosu)
s=pd.DataFrame([cls,dosu, cum_dosu], index=["階級", "度数", "累積度数"])
s
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
階級 | 43 | 45 | 47 | 49 | 51 | 53 | 55 | 57 | 59 | 61 | 63 | 65.0 |
度数 | 1 | 3 | 6 | 9 | 21 | 12 | 19 | 15 | 10 | 2 | 2 | NaN |
累積度数 | 1 | 4 | 10 | 19 | 40 | 52 | 71 | 86 | 96 | 98 | 100 | NaN |
# 2軸グラフ(右軸の付加)
my_ticks = np.arange(43,65,2)
plt.xticks(np.append(my_ticks,65))
plt.yticks(np.arange(0,21,5))
plt.title("Weight distribution in a class", fontsize=18)
plt.xlabel("weight [kg]", fontsize=14)
plt.ylabel("Number of students", fontsize=14)
plt.bar(my_ticks, dosu, align='edge',color="c", ec="black", width=2)
plt.twinx()
plt.ylim(0,110)
plt.ylabel("Cumulative", fontsize=14)
plt.plot(my_ticks, cum_dosu, color="k", lw=2);
2つのデータセットのヒストグラム
from scipy.stats import norm
import random
from numpy.random import randint
height_men = norm.rvs(loc=171.4, scale=5.8, size=500)
height_women = norm.rvs(loc=157.8, scale=6.1, size=500)
plt.hist(height_men, bins=np.arange(140,200,2.5), alpha=0.4, color='c', label='男性')
plt.hist(height_women, bins=np.arange(140,200,2.5), alpha=0.4, color='m', label='女性')
plt.xlabel('身長 (cm)', fontsize=14)
plt.ylabel('度数', fontsize=14)
plt.legend(loc='best');
# データの準備
df_box = pd.DataFrame(
{'国語': [94, 63, 55, 61, 56, 53, 98, 55, 76, 91, 66, 71, 83, 69, 56,
74, 57, 77, 83, 46, 45, 53, 68, 28, 99, 77, 69, 66, 65, 49],
'数学': [76, 57, 66, 87, 58, 100, 24, 44, 67, 88, 69, 85, 13, 73, 61,
84, 50, 65, 77, 91, 98, 97, 80, 50, 72, 6, 73, 68, 59, 83],
'理科': [62, 59, 82, 80, 69, 66, 68, 53, 43, 68, 64, 56, 72, 56, 54,
73, 62, 60, 56, 58, 67, 78, 73, 78, 12, 57, 8, 81, 68, 84],
'社会': [81, 80, 78, 65, 97, 77, 88, 97, 67, 84, 64, 85, 72, 94, 61,
75, 73, 56, 84, 74, 89, 69, 65, 79, 79, 34, 69, 67, 68, 86],
'英語': [62, 74, 66, 78, 61, 74, 82, 90, 82, 26, 85, 82, 76, 73, 64,
91, 53, 67, 54, 76, 64, 49, 70, 83, 71, 86, 100, 69, 77, 56]})
kokugo = df_box['国語'].to_numpy()
math = df_box['数学'].to_numpy()
rika = df_box['理科'].to_numpy()
syakai = df_box['社会'].to_numpy()
eigo = df_box['英語'].to_numpy()
subjects = (kokugo, math, rika, syakai, eigo)
plt.boxplot(subjects)
plt.xticks([1,2,3,4,5], ('国語', '数学', '理科', '社会', '英語'))
plt.title('科目別得点分布', fontsize=14)
plt.xlabel('科目', fontsize=12)
plt.ylabel('得点分布', fontsize=12)
plt.ylim([0,105])
plt.grid(False)
大数の法則
def setgraph(n):
sa = np.setdiff1d(np.array(range(1,7)), randint(1,7,n))
labels, counts = np.unique(randint(1,7,n), return_counts=True)
labels = np.append(labels,sa)
counts = np.append(counts,np.zeros(len(sa)))
plt.title(f'{trial_num}回', fontsize=16)
plt.xlabel('サイコロの目', fontsize=16)
plt.ylabel('回数', fontsize=16)
plt.bar(labels, counts, align='center', color='y')
plt.gca().set_xticks(labels)
plt.figure(figsize=(12,3))
plt.subplot(1, 4, 1)
trial_num = 100
setgraph(trial_num)
plt.subplot(1, 4, 2)
trial_num = 1000
setgraph(trial_num)
plt.subplot(1, 4, 3)
trial_num = 10000
setgraph(trial_num)
plt.subplot(1, 4, 4)
trial_num = 100000
setgraph(trial_num)
plt.tight_layout();
【推測統計】標本平均による母平均の推定
n_data=5000000 # 母集団:500万人分の身長データ
height_men = norm.rvs(loc=171.4, scale=5.8, size=n_data)
population_mean = np.mean(height_men)
population_sdt = np.std(height_men)
ncol=3; nrow=3; n_sample = 100
index_sampled = []
index = np.arange(n_data)
for i in range(ncol * nrow):
np.random.shuffle(index)
index_sampled.append(index[:n_sample].copy())
_, axes = plt.subplots(nrow, ncol, figsize=(nrow*3, ncol*2))
for i in range(nrow):
for j in range(ncol):
ax = axes[i, j]
height_men_samplee = height_men[index_sampled[i*ncol+j]]
m = np.mean(height_men_samplee)
sns.histplot(height_men_samplee, kde=True, color='g', alpha=0.2, ax=ax)
ax.set_title(f'平均:{m:.3f}')
ax.vlines(m, 0, ax.get_ylim()[1], 'r')
ax.set_xlim(150, 190)
plt.tight_layout();
plt.title('Effects of excitation power', fontsize=18)
plt.xlabel('Power (mW)', fontsize=16)
plt.ylabel('Generation rate ($s^{-1}$)', fontsize=16)
x= np.arange(0, 11, 2)
y = x**2
plt.plot(x, y, ms=5, zorder=0, marker='D',color='r', lw="2");
y_err = np.array([1/2,1,2,3,4,5])*3
x_err = np.array([1/2,1,2,3,4,5])/10
plt.errorbar(x, y, yerr = y_err, xerr = x_err, zorder=1,
capsize=5, fmt='o', markersize=10, ecolor='black',
markeredgecolor = "black", color='w')
plt.tick_params(labelsize = 12)
plt.xlim(-.5,11)
plt.ylim(-10,120)
plt.grid(False)
# 正弦波
x = np.linspace(-2*np.pi, 2*np.pi, 256)
y = np.sin(x)
# グラフのタイトル、軸名称の設定
plt.title('正弦波グラフ', fontsize=16)
# グラフの軸
plt.xlabel('X-Axis', fontsize=14)
plt.ylabel('Y-Axis', fontsize=14)
# x軸ラベルの設定(TeX書式も使用可能)
plt.xticks([k*np.pi/2 for k in range(-4,5)],
['$-2\pi$','$-3\pi$/2','$-\pi$', '$-\pi/2$', '$0$', '$+\pi/2$', '$+\pi$', '$+3\pi/2$', '$+2\pi$'])
plt.grid()
# 色の塗り分け
plt.plot(x, y, c='k', linewidth=1, linestyle=':')
plt.fill_between(x, y, 0 , y > 0, color='blue', alpha=.25)
plt.fill_between(x, y, 0 , y < 0, color='red', alpha=.25);
# (x,y)に加えて第3の値(z)を持つようなデータの可視化
# z軸データとして、原点からの距離(の2乗)を使用
x = np.random.rand(100)
y = np.random.rand(100)
plt.figure(figsize=(9,3))
plt.subplot(1, 2, 1)
value = x**2 + y**2
plt.scatter(x, y, s=300, marker='$\clubsuit$', c=value, cmap='Blues')
# カラーバーを表示
plt.colorbar();
plt.subplot(1, 2, 2)
# z軸データとして、原点からの距離(の2乗)を使用
value = (x**2 + y**2) * 2000
plt.scatter(x, y, s=value, marker='$Sousei$', color='m', alpha=0.5);
plt.tight_layout();
# excelファイルの直接読み込み(最初のシート、文字コード指定)
df_dow = pd.read_excel('data/Dow_HistoricalData.xlsx', header=0, engine='openpyxl')
df_dow['Date'] = pd.to_datetime(df_dow['Date'])
year = df_dow['Date'].to_numpy()
df_dow = df_dow.set_index('Date')
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
plt.figure(figsize=(10,4))
plt.subplot(1, 2, 1)
# グラフタイトル
plt.title('ダウ工業株30種平均 (1896-2021)', fontsize=16)
# グラフの軸名
plt.xlabel('Year', fontsize=14)
plt.ylabel('株価(線形表示)', fontsize=14)
# グラフの塗りを指定
plt.fill_between(year, df_dow['Close'], facecolor='gray', alpha=0.3, interpolate=True)
plt.plot(year, df_dow['Close'], c="k", lw=1.5)
plt.xticks(rotation=20) # 回転角度指定
plt.subplot(1, 2, 2)
plt.title('ダウ工業株30種平均 (1896-2021)', fontsize=16)
plt.xlabel('Year', fontsize=14)
plt.ylabel('株価(対数表示)', fontsize=14)
plt.fill_between(year, df_dow['Close'], facecolor='gray', alpha=0.3, interpolate=True)
plt.plot(year, df_dow['Close'], c="k", lw=1.5)
plt.xticks(rotation=20)
plt.yscale('log') # 対数表示
plt.tight_layout();
df = pd.read_excel("data/pref_population.xlsx")
df.set_index(['都道府県'], inplace=True)
df.plot.bar(y=df.columns.values, ylim=(0,14000), figsize=(14,4),fontsize=12)
plt.xlabel('都道府県', fontsize=14)
plt.ylabel('人口(千人)', fontsize=14);
df['増減率']= df['平成28年']/df['平成12年']
c_list = ['c' if df['増減率'][i] >=1 else "y" for i in range(len(df))]
df.plot.bar(y='増減率', ylim=(0.8,1.2), figsize=(14,4),fontsize=12, color=c_list, legend=False)
plt.xlabel('都道府県', fontsize=14)
plt.axhline(y=1, c='k', ls=':')
plt.ylabel('増減率 (H28/H12)', fontsize=14);
import geopandas as gpd
# データ(pop_est:Geopandasのサンプルデータとして付属)の地図上への描画
df_wld = gpd.read_file('data/worldmap/naturalearth_lowres.shp')
my_data = np.random.randint(10, size=len(df_wld))
df_wld['data'] = my_data
# エクセルファイルの読み込み
df_wld2 = pd.read_excel('data/mydata_wld.xlsx')
# ここで、両方のdataframeで共通な国コード(code, iso_a3)をkeyとして用いてデータを統合
df_wld_merged = pd.merge(df_wld, df_wld2, left_on='iso_a3', right_on='code')
# 指定データ列の地図上への描画:データ指定 column=' '
df_wld_merged.plot(column='data', figsize=(12, 6), cmap='Blues',legend=False)
# title etc.
plt.title("Some data you made", fontsize=18)
plt.xlabel('longitude', fontsize=16)
plt.ylabel('latitude', fontsize=16);
# 辞書形式によるdataframeの作成
df_wld_myplot = pd.DataFrame(
{'City': ['Tokyo', 'Brasilia', 'Santiago', 'Bogota', 'Caracas'],
'Country': ['Japan', 'Brazil', 'Chile', 'Colombia', 'Venezuela'],
'Latitude': [35.6, -15.78, -33.45, 4.60, 10.48],
'Longitude': [138.8, -47.91, -70.66, -74.08, -66.86]})
my_wldPlot = gpd.GeoDataFrame(df_wld_myplot,
geometry=gpd.points_from_xy(df_wld_myplot.Longitude, df_wld_myplot.Latitude))
capitals = gpd.read_file('data/worldmap/naturalearth_cities.shp')
base = df_wld[df_wld.name!="Antarctica"].plot(color='white', edgecolor='black', figsize=(12, 6))
capitals.plot(ax=base, marker='o', color='red', markersize=5)
my_wldPlot.plot(ax=base, marker='D', color='blue', markersize=30);
# 地理情報データ付きのgeojsonファイルを読み込み
df_jpgeo = gpd.read_file('data/japan.geojson')
df_jpgeo['value'] = df_jpgeo['id']
df_jp_myplot = pd.DataFrame(
{'都市': ['Niigata','Sapporo', 'Tokyo'],
'緯度': [37.92240, 43.06417, 35.6895],
'経度': [139.04320, 141.34695,139.69171]})
my_jpPlot = gpd.GeoDataFrame(df_jp_myplot,
geometry=gpd.points_from_xy(df_jp_myplot.経度, df_jp_myplot.緯度))
base = df_jpgeo.plot(color='white', linewidth=0.7, edgecolor='black',figsize=(8, 8))
my_jpPlot.plot(ax=base, marker='s', color='b', markersize=20);
plt.xlim([127, 150])
plt.ylim([29.5, 46.5])
# バブルチャート形式で描画
plotsize = [5200, 3200, 600]
my_jpPlot.plot(ax=base, marker='o', color='b', ec='b', markersize=plotsize, alpha=0.25)
# タイトル、軸情報
plt.xlabel('longitude', fontsize=14)
plt.ylabel('latitude', fontsize=14)
plt.title("Japan map", fontsize=18);
# 新潟県の地理情報データ(地図作製用)
df_geo = gpd.read_file('data/niigata_GML/N03-19_15_190101.geojson')
niigataCities = df_geo['N03_004'].unique()
niigataNumCities = len(niigataCities)
ngtPref_data = [k for k in range(niigataNumCities)]
mydata = np.stack([niigataCities, ngtPref_data], axis=1)
df_ngtPref = pd.DataFrame(mydata, columns=['city', 'data'])
df_ngtPref = pd.merge(df_geo, df_ngtPref, left_on='N03_004', right_on='city').drop(columns='city')
# データの地図上への描画
df_ngtPref.plot(column="data", edgecolor='black', figsize=(12, 6), cmap='Blues')
plt.xlabel('longitude', fontsize=14)
plt.ylabel('latitude', fontsize=14)
plt.title('Dummy data distribution in Niigata Prefecture', fontsize=14);
# Contour plot (等高線図)の例
N = M = 201
x = np.linspace(0, 20, N)
y = np.linspace(0, 20, M)
X, Y = np.meshgrid(x,y)
data = np.sin(np.pi * X*2 / 10) * np.cos(np.pi * Y*2 / 10)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7, 3))
im = ax1.imshow(data, extent=[0, 200, 0, 200],cmap='jet')
ax1.set_title("Contour plot: 'jet'")
fig.colorbar(im, ax=ax1, shrink=0.8)
im2 = ax2.imshow(data, extent=[0, 200, 0, 200], cmap='viridis')
fig.colorbar(im2, ax=ax2, shrink=0.8)
ax2.set_title("Contour plot: 'viridis'")
fig.tight_layout()
# 3D グラフ
from mpl_toolkits.mplot3d import axes3d
x = np.arange(-4,4,0.1)
y = np.arange(-4,4,0.1)
X,Y = np.meshgrid(x,y)
Z = X*np.exp(-X**2 - Y**2)
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z);
import sympy as sym
from sympy import init_printing
# 指定した文字をシンボルとして扱う
a, b, c, x, y, z = sym.var("a b c x y z")
# y = sinx/x
y = sym.sin(x)/x
# グラフをプロット
p = sym.plot(y, (x, -12, 12), ylabel = "y");
# ベクトル場
# https://krajit.github.io/sympy/vectorFields/vectorFields.html
plt.figure(figsize=(8,4))
plt.subplot(1, 2, 1)
lattice = np.linspace(-5,5,10)
x, y = np.meshgrid(lattice, lattice)
u = x/np.sqrt(x**2 + y**2)
v = y/np.sqrt(x**2 + y**2)
plt.quiver(x,y,u,v);
plt.subplot(1, 2, 2)
u = -y/np.sqrt(x**2 + y**2)
v = x/np.sqrt(x**2 + y**2)
plt.quiver(x,y,u,v);
#1. 伝染病流行過程を記述する古典的モデル方程式(SIR model)
from scipy.integrate import odeint
def sir_model(data, t, alpha, beta):
# alpha: 感染率、beta: 回復率
# R0 = N * alpha/beta:基本再生産数
x, y, z = data
dxdt = - alpha*x*y
dydt = alpha*x*y - beta*y
dzdt = beta*y
return [dxdt, dydt, dzdt]
N = 1000000
alpha=0.2/N
beta=0.05
S0 = 10
dt=1
print(f'基本再生産数(R0): {N*alpha/beta}')
init_vals=[N-S0, S0, 0]
times = np.arange(0.0, 180, dt)
results = odeint(sir_model, init_vals, times, args=(alpha, beta))
plt.title("SIR MODEL")
plt.plot(times, results[:,0], color='g', linewidth=1.0, label='Susceptible')
plt.plot(times, results[:,1], color='r', linewidth=1.0, label='Infected')
plt.plot(times, results[:,2], color='b', linewidth=1.0, label='Recovered')
plt.xlim(0,180)
plt.legend()
plt.xlabel('Days passed', fontsize=12)
plt.ylabel('Number of people', fontsize=12)
plt.grid(True);
基本再生産数(R0): 4.0
#2-1. 確率過程のシミュレーション(2次元ランダムウォーク(酔歩運動))
# Sep step number
step = 1000
# Make list for recording x-y coordinates
mfp = 2.0 # mean free path
x=0.0; y=0.0
x_walk = [x]; y_walk = [y]
# Random Walk
for i in range(step):
x += (random.random() - 0.5) * mfp
y += (random.random() - 0.5) * mfp
x_walk.append(x)
y_walk.append(y)
# Display Graph
plt.figure(figsize=(5,5))
plt.plot(x_walk, y_walk);
#2-2. 経済格差の自然発生シミュレーション
from matplotlib import animation
def giving_money(agents):
agent1, agent2 = random.sample(agents, k=2)
if agent1.wealth >= 1:
agent2.wealth += 1
agent1.wealth -= 1
def gini(y):
y.sort()
n = len(y)
nume = 0
for i in range(n):
nume = nume + (i + 1) * y[i]
deno = n * sum(y)
return ((2*nume)/deno - (n+1)/n)*(n/(n-1))
def count_value(labels, data):
counts = []
for i in range(len(labels)):
counts.append(data.count(i))
return counts
def animate(i):
for rect, yi in zip(rects, data[i]):
rect.set_height(yi)
time_text.set_text(f'time= {T[i]:.2f}')
gini_text.set_text(f'Gini係数: {G[i]:.4f}')
return rects, time_text, gini_text
class Agent:
def __init__(self, unique_id, initial_wealth):
self.unique_id = unique_id # id番号
self.wealth = initial_wealth # 初期資産
n = 300 # エージェント数(人数)
time = 1000 # 取引回数
agents = [Agent(i, 1) for i in range(n)]
labels = range(10)
G = []; T = []; count_list = []
for i in range(time):
if i % 10 == 0 or i == range(time)[-1]:
agent_wealth = [a.wealth for a in agents]
T.append(i)
G.append(gini(agent_wealth))
count_list.append(count_value(labels, agent_wealth))
giving_money(agents)
fig = plt.figure()
data = count_list
# Initial data
rects = plt.bar(labels, data[0], color='c')
time_text = plt.text(7, 280, T[0])
gini_text = plt.text(7, 260, G[0])
ani = animation.FuncAnimation(fig, animate, frames=len(data), interval=100)
# gifファイルとしてアニメーションを保存
ani.save('bar_anime.gif', writer='pillow')
# ウェブスクレイピング(Webサイトからの自動情報取得)
import requests
from bs4 import BeautifulSoup
url = "https://news.yahoo.co.jp/categories/it"
r = requests.get(url)
soup = BeautifulSoup(r.text,"html.parser")
for item in soup.find_all(class_="sc-jqCOkK jEGAcM"):
uri = item.get("href")
title = item.get_text()
print(f'{title} \t [{uri}]({url}) ')
パナ カナダ子会社にサイバー攻撃 [https://news.yahoo.co.jp/pickup/6423151](https://news.yahoo.co.jp/categories/it) ハリポタ ロシアから電子書籍撤退 [https://news.yahoo.co.jp/pickup/6423116](https://news.yahoo.co.jp/categories/it) 量子コンピューター今年度整備へ [https://news.yahoo.co.jp/pickup/6423110](https://news.yahoo.co.jp/categories/it) セブン&アイのアプリ障害が復旧 [https://news.yahoo.co.jp/pickup/6423081](https://news.yahoo.co.jp/categories/it) 米Intelが露で事業停止 戦争非難 [https://news.yahoo.co.jp/pickup/6423064](https://news.yahoo.co.jp/categories/it) 全国ゆるキャラも「戦争やめて」 [https://news.yahoo.co.jp/pickup/6423023](https://news.yahoo.co.jp/categories/it) 抜け穴封じ 米が露の闇ウェブ制裁 [https://news.yahoo.co.jp/pickup/6423007](https://news.yahoo.co.jp/categories/it) アマゾン ロケット3社と大型契約 [https://news.yahoo.co.jp/pickup/6423052](https://news.yahoo.co.jp/categories/it)
別の例:
[Yahoo! 天気] https://weather.yahoo.co.jp/weather/15/5410.html
[新潟県のPM2.5予報と黄砂情報] https://china-pm25.com/area/niigata/ から取得
import requests, re
from bs4 import BeautifulSoup
url = "https://weather.yahoo.co.jp/weather/15/5410.html"
r = requests.get(url)
soup = BeautifulSoup(r.content,"html.parser")
for i, u in enumerate(soup.find_all("dt")):
if str(u)=='<dt>風:</dt>':
break
wind = re.split('<|>',str(soup.find_all('dd')[i]))[2]
s_strs = str(soup.find_all(class_="high")[0])
high = re.split('<em>|</em>', s_strs)[1]
s_strs = str(soup.find_all(class_="low")[0])
low = re.split('<em>|</em>', s_strs)[1]
foi = re.split('<|>',str(soup.find_all(class_="pict")[0]))[4]
s_strs = soup.find_all(class_="index_value")
sisu_list = [s_strs[i].get_text() for i in range(len(s_strs))]
day1 = sisu_list[:len(sisu_list) // 2]
day2 = sisu_list[len(sisu_list) // 2:-1]
#print(day1)
# 発表時刻の取得
tm = str(soup.find_all(class_="yjSt yjw_note_h2")[-1])
ss=re.split('<p class="yjSt yjw_note_h2">|</p>', tm)[1]
#print(ss)
line = "{0}\n今日の天気:{1}\n気温(℃) 最高:{2} / 最低:{3}\n風:{4}\n".format(ss, foi, int(high), int(low), wind)
#print(line)
str_sisu = soup.find_all(class_="index_text")
sisuInfo_list = [str_sisu[i].get_text() for i in range(len(str_sisu))]
info = [sisu + ' ' + info for sisu, info in zip(sisu_list, sisuInfo_list)]
sisuInfo_day1 = info[:len(info)//2]
sisuInfo_day2 = info[len(info)//2:-1]
#print(sisuInfo_day1)
# Yahoo! 天気 花粉情報
try:
url = "https://weather.yahoo.co.jp/weather/pollen/4/15/15107/"
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
tmp = soup.select("#main > div:nth-child(6) > ul > li:nth-child(1) > dl > dd.plnLevel.plnLevel-01 > div > p:nth-child(1)")
pm_info0 = f'花粉:{tmp[0].text} / '
except requests.exceptions.RequestException:
pm_info = ''
# 新潟県のPM2.5予報と黄砂情報
try:
url = "https://china-pm25.com/area/niigata/"
r = requests.get(url)
soup = BeautifulSoup(r.content,"html.parser")
s_strs = soup.find_all(class_="fable")[1].get_text().split()
#print(s_strs)
pm_info = pm_info0 + "PM2.5:{0} / 黄砂:{1}\n".format(s_strs[8], s_strs[15])
#print(pm_info)
except requests.exceptions.RequestException:
pm_info = pm_info0
line += pm_info + "\n"+'\n'.join(sisuInfo_day1)
print(line)
2022年4月7日 14時00分 発表 今日の天気:曇時々雨 気温(℃) 最高:16 / 最低:7 風:北の風後南西の風海上では南西の風やや強く 花粉:少ない / PM2.5:やや多い / 黄砂:少ない 洗濯指数30 外干しは厳しそう 傘指数90 絶対傘を忘れずに 紫外線指数40 日焼け止めを利用しよう 重ね着指数60 ジャケットなど羽織るものがあると安心 乾燥指数60 リップやクリームを持ち歩こう 風邪注意指数60 手洗い・うがいをしっかり
from numpy import sin, cos, pi
from scipy.integrate import quad
def fourier(fun, n_max):
a = []
b = []
for n in range(n_max+1):
res, err = quad(lambda x:fun(x)*cos(n*x), -pi, pi)
a.append(res/pi)
res, err = quad(lambda x:fun(x)*sin(n*x), -pi, pi)
b.append(res/pi)
return a, b
def fn(a, b, x):
sum = a[0] / 2
for n in range(1, len(a)):
sum += a[n] * cos(n*x) + b[n] * sin(n*x)
return sum
# 矩形関数を入力
def myfunc(x):
x = (x + pi) % (pi * 2) - pi
if x >= 0:
return 1
else:
return 0
# Fourier coefficients
n_max = 16
a, b = fourier(myfunc, n_max)
x_min = -2*pi - 1/2
x_max = 2*pi + 1/2
xs = np.linspace(x_min, x_max, 2**10)
conv = fn(a, b, xs)
y_min = -0.2
y_max = 1.2
plt.axis([x_min, x_max, y_min, y_max])
infunc = np.array(list(map(myfunc, xs)))
plt.plot(xs, infunc, 'b:', lw=1)
plt.plot(xs, conv, 'r-', lw=1);
import qrcode
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_M,
box_size=4, border=2)
# ここに埋め込みたい情報を設定(URLの場合は直接そのサイトに飛ぶ)
qr.add_data('データサイエンス実践A')
# qr.add_data('https://create.niigata-u.ac.jp/')
qr.make(fit=True)
img = qr.make_image(fill_color="blue", back_color="yellow")
img