2018年10月19日金曜日

開発環境

  • macOS Mojave - Apple
  • Emacs (Text Editor)
  • Python 3.7 (プログラミング言語)

Pythonからはじめる数学入門 (Amit Saha (著)、黒川 利明 (翻訳)、オライリージャパン)の2章(データを統計量で記述する)、3.9(プログラミングチャレンジ)、問題3-3(他のCSVデータでの実験)を取り組んでみる。

コード(Emacs)

Python 3

#!/usr/bin/env python3
from stats import mean, median, mode, variance_sd
import csv
import matplotlib.pyplot as plt

print('3.')
filename = 'WWDI-USA_SP_POP_TOTL.csv'
with open(filename) as f:
    reader = csv.reader(f)
    next(reader)
    years = []
    populations = []
    for row in reader:
        years.append(row[0])
        populations.append(float(row[1]))

years.reverse()
populations.reverse()

years_diff = []
populations_diff = []

for i in range(len(years) - 1):
    years_diff.append(
        f'{years[i].split("-")[0][-2:]}-{years[i+1].split("-")[0][-2:]}')
    populations_diff.append(populations[i+1] - populations[i])

for a, b in [('平均', mean),('中央値', median),('最頻値', mode)]:
    print(f'{a}: {b(populations_diff)}')
for a, b in zip(('分散', '標準偏差'), variance_sd(populations_diff)):
    print(f'{a}: {b}')

plt.plot(years_diff, populations_diff)
plt.xticks(range(len(years_diff)), years_diff, rotation=90)
plt.savefig('sample3.svg')

入出力結果(Terminal, Jupyter(IPython))

$ ./sample3.py
3.
平均: 2568103.529411765
中央値: 2482740.0
最頻値: 1945000.0
分散: 191080368978.05304
標準偏差: 437127.40588763484
$

0 コメント:

コメントを投稿