実習問題

基礎文法

例題

ある樹種のどんぐりを 3 つ拾って、その重さを測ったところ、それぞれ 3.4g、3.1g、2.9g であった。この平均値を求めよ。

In [1]:
a = 3.4
b = 3.1
c = 2.9

s = a + b + c
n = 3

ave = s / n
print(ave)
3.1333333333333333

問題 1-1

ある年の各県のコシヒカリの生産量(kg/10a)は調査したところ以下のようになった。この年のコシヒカリの平均生産量(kg/10a)を求めよ。

都道府県 生産量
新潟 528.3
茨城 520.7
福島 538.8
栃木 535.2
千葉 512.0
In [2]:
niigata = 528.3
ibaraki = 520.7
fukushima = 538.8
tochigi = 535.2
chiba = 512.0

total = niigata + ibaraki + fukushima + tochigi + chiba
ave = total / 5

print(ave)
527.0

問題 1-2

ある年の各県のコシヒカリ、ひとめぼれ、あきたこまちの生産量(kg/10a)は調査したところ以下のようになった。この年のコシヒカリ、ひとめぼれ、あきたこまちの平均生産量(kg/10a)をそれぞれ求めよ。

都道府県 品種 生産量
新潟 コシヒカリ 528.3
茨城 コシヒカリ 520.7
福島 コシヒカリ 538.8
栃木 コシヒカリ 535.2
千葉 コシヒカリ 512.0
宮城 ひとめぼれ 519.4
岩手 ひとめぼれ 520.5
福島 ひとめぼれ 561.6
秋田 あきたこまち 567.5
岩手 あきたこまち 538.3
岡山 あきたこまち 501.9
In [3]:
koshihikari = [528.3, 520.7, 538.8, 535.2, 512.0]
hitomebore = [519.4, 520.5, 561.6]
akitakomachi = [567.5, 538.3, 501.9]

koshihikari_ave = sum(koshihikari) / len(koshihikari)
hitomebore_ave = sum(hitomebore) / len(hitomebore)
akitakomachi_ave = sum(akitakomachi) / len(akitakomachi)

print(koshihikari_ave)
print(hitomebore_ave)
print(akitakomachi_ave)
527.0
533.8333333333334
535.9

問題 1-3

アップルパイ(税抜180円)およびメロンパン(税抜210円)を購入し、店内で食べる場合、合計いくら払えば良いかを計算せよ。ただし、店内で食べる場合の消費税は 10% であり、持ち帰りの場合の消費税は 8% である。

In [4]:
apple = 180
melon = 210
tax = 0.10

subtotal = apple + melon
total = subtotal + subtotal * 0.10

print(total)
429.0

問題 1-4

アップルパイ(税抜180円)およびメロンパン(税抜210円)を購入し、合計いくら払えば良いかを計算せよ。ただし、持ち帰りかどうかを判定する if または if-else 文を使うこと。また、店内で食べる場合の消費税は 10% であり、持ち帰りの場合の消費税は 8% である。

In [5]:
# 解答 1

apple = 180
melon = 210
takeout = True
eatin = False

subtotal = apple + melon

if takeout is True:
    total = subtotal * 1.08

if eatin is True:
    total = subtotal * 1.10
    
print(total)
421.20000000000005
In [6]:
# 解答 2 (takeout が True ならば必ず eatin は False、そのため eatin 変数を削除)

apple = 180
melon = 210
takeout = True

subtotal = apple + melon

if takeout is True:
    total = subtotal * 1.08

else:
    total = subtotal * 1.10
    
print(total)
421.20000000000005

問題 1-5

アップルパイ(税抜180円)を 3 つ、メロンパン(税抜210円)を 3 つ購入し、店内で食べるの場合、合計いくら払えば良いかを計算せよ。ただし、小計金額が 1000 円を超える場合は 5% 割引される。また、店内でたべるかどうかの判定は問題 1-4 のように takeout 変数を使って if 文で判断すること。また、小計金額が 1000 円を超えたかどうかも if 文で判断すること。

In [7]:
apple = 180 * 3
melon = 210 * 3
takeout = False

subtotal = apple + melon

if subtotal > 1000:
    subtotal = subtotal * 0.95

    
if takeout is True:
    total = subtotal * 1.08
else:
    total = subtotal * 1.10

print(total)
1222.65

問題 1-6

ある年の各県のコシヒカリの生産量(kg/10a)は調査したところ以下のようになった。これらのデータをリストとして 1 つのオブジェクトに代入せよ。そして、for 文および while 文を使用して、平均値を求めよ。(sum 関数と len 関数を使わないこと)

都道府県 生産量
新潟 528.3
茨城 520.7
福島 538.8
栃木 535.2
千葉 512.0
In [8]:
koshihikari = [528.3, 520.7, 538.8, 535.2, 512.0]

s = 0
n = 0

while n < 5:
    s = s + koshihikari[n]
    n = n + 1
    
ave = s / 5
print(ave)
527.0
In [9]:
koshihikari = [528.3, 520.7, 538.8, 535.2, 512.0]
s = 0

for w in koshihikari:
    s = s + w

ave = s / 5
print(ave)
527.0

問題 1-7

同じ長さのリスト a とリスト b が与えられたとき、両者の各位置の要素同士の積を求め、z に代入せよ。z が [8, 3, 24, 12, 4] となればよい。

In [10]:
a = [2, 3, 8, 2, 1]
b = [4, 1, 3, 6, 4]
z = [0, 0, 0, 0, 0]

i = 0

while i < 5:
    z[i] = a[i] * b[i]
    i = i + 1
    
print(i)
5

問題 1-8

リスト a の中の奇数の値の個数を求めよ。

In [11]:
a = [3, 19, 4, 69, 39, 30, 28, 74, 32]

n_odd = 0

i = 0

while i < len(a):
    if a[i] % 2 == 1:
        n_odd = n_odd + 1
    i = i + 1
    
print(n_odd)
4
In [12]:
a = [3, 19, 4, 69, 39, 30, 28, 74, 32]

n_odd = 0

for w in a:
    if w % 2 == 1:
        n_odd = n_odd + 1

print(n_odd)
4

問題 1-9

リスト a の中の最大値と最小値を求めよ。ただし、max 関数および min 関数を使わないこと。

In [13]:
a = [3, 9, 6, 4, 1, 5]

a_max = a[0]
a_min = a[0]

for w in a:
    
    if w > a_max:
        a_max = w
    
    if w < a_min:
        a_min = w

print(a_max)
print(a_min)
9
1

問題 1-10

1 から 100 までの間にある素数をすべて出力せよ。

In [14]:
N = 100
i = 2

while i <= N:
    
    n_divided = 0
    
    j = 2
    while j < i:
        if i % j == 0:
            n_divided = n_divided + 1
        j = j + 1
    
    if n_divided == 0:
        print(i)
        
    i = i + 1
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

問題 1-11 (難問)

リスト a の要素を昇順に並べ替えよ。

In [15]:
a = [4, 6, 9, 1, 0, 7, 2, 5, 8, 3]

changed = True

while changed:
    changed = False    
    i = 0
    while i < len(a) - 1:
        if a[i] > a[i + 1]:
            
            a[i], a[i + 1] = a[i + 1], a[i]
            changed = True
        i = i + 1


print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Pandas - NumPy - matplotlib

問題 2-1

配列 t の平均を求めよ。

In [16]:
import numpy as np
t = [21.3, 21.6, 20.9]
t = np.array(t)

np.mean(t)
Out[16]:
21.26666666666667

問題 2-2

2 週間の気温データが配列 t に保存されている。3 日ごとの移動平均を求めよ。

In [17]:
import numpy as np

t = [21.3, 21.6, 20.9, 21.7, 23.9, 22.3, 21.7,
     22.4, 22.3, 24.3, 23.4, 24.8, 23.0, 22.9]
t = np.array(t)

ave = []

i = 0
while i < len(t) - 2:
    ave.append(np.mean(t[i:(i+3)]))
    i = i + 1

print(ave)
[21.26666666666667, 21.400000000000002, 22.166666666666668, 22.63333333333333, 22.633333333333336, 22.133333333333336, 22.13333333333333, 23.0, 23.333333333333332, 24.166666666666668, 23.733333333333334, 23.566666666666663]

問題 2-3

2 週間の気温データが配列 t に保存されている。ヒストグラムを描け。 (※ 一部の Jupyter Notebook 環境において %matplotlib inline を実行しないとグラフが表示されない場合がある。)

In [18]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

t = [21.3, 21.6, 20.9, 21.7, 23.9, 22.3, 21.7,
     22.4, 22.3, 24.3, 23.4, 24.8, 23.0, 22.9]
t = np.array(t)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.hist(t)
plt.show()

問題 2-4

2 週間の気温データが配列 t に保存されている。t の値を縦軸とし、t の各要素に対応する横軸を 1〜14 とする線グラフを描け。

In [19]:
import numpy as np
import matplotlib.pyplot as plt

t = [21.3, 21.6, 20.9, 21.7, 23.9, 22.3, 21.7,
     22.4, 22.3, 24.3, 23.4, 24.8, 23.0, 22.9]
t = np.array(t)
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
# x = np.arange(1, 15)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, t)
plt.show()

問題 2-5

2 週間の気温データが配列 t に保存されている。t の値を縦軸とし、t の各要素に対応する横軸を 1〜14 とする線グラフを描け。また、3 日ごとの移動平均も線グラフとして書き入れよ。

In [20]:
import numpy as np
import matplotlib.pyplot as plt

t = [21.3, 21.6, 20.9, 21.7, 23.9, 22.3, 21.7,
     22.4, 22.3, 24.3, 23.4, 24.8, 23.0, 22.9]
t = np.array(t)
x = np.arange(1, 15)

ave = []
i = 0
while i < len(t) - 2:
    ave.append(np.mean(t[i:(i+3)]))
    i = i + 1
ave_x = np.arange(3, 15)

fig = plt.figure()
ax = fig.add_subplot()
ax.plot(x, t, label='observed')
ax.plot(ave_x, ave, label='moving_average')
ax.legend()
plt.show()

テキストデータ処理

問題 3-1

workshop フォルダ内に置かれてある diversity_galapagos.txt ファイルを Pandas の read_csv で読み込んで、最初の数行を Jupyter Notebook 上に表示(print)せよ。ただし、このファイルはタブ区切りのテキストファイルで、# から始まるコメント行があることに注意すること。

In [21]:
import pandas as pd

file_path = 'diversity_galapagos.txt'

df = pd.read_csv(file_path,
        sep='\t', comment='#', header=0)
df.head()
Out[21]:
Island Species Endemics Area Elevation Nearest Scruz Adjacent
0 Baltra 58 23 25.09 346 0.6 0.6 1.84
1 Bartolome 31 21 1.24 109 0.6 26.3 572.33
2 Caldwell 3 3 0.21 114 2.8 58.7 0.78
3 Champion 25 9 0.10 46 1.9 47.4 0.18
4 Coamano 2 1 0.05 77 1.9 1.9 903.82

問題 3-2

diversity_galapagos.txt ファイルを読み込み、Species 列を縦軸の座標とし、Area 列を横軸の座標として、散布図を描け。ただし、値のスケールが大きい場合は、Species または Area の値を対数化して描いてみてもよい。

In [22]:
file_path = 'diversity_galapagos.txt'
df = pd.read_csv(file_path, sep='\t', comment='#', header=0)

y = np.log10(df.iloc[:, 1])
x = np.log10(df.loc[:, 'Area'])

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x, y)
plt.show()

問題 3-3

iris.txt ファイルを読み込んで、中身を表示せよ。

In [23]:
import pandas as pd
file_path = 'iris.txt'
df = pd.read_csv(file_path, sep='\t', comment='#', header=0)
df
Out[23]:
ID Sepal.Length Sepal.Width Petal.Length Petal.Width Species
0 1 5.1 3.5 1.4 0.2 setosa
1 2 4.9 3.0 1.4 0.2 setosa
2 3 4.7 3.2 1.3 0.2 setosa
3 4 4.6 3.1 1.5 0.2 setosa
4 5 5.0 3.6 1.4 0.2 setosa
... ... ... ... ... ... ...
145 146 6.7 3.0 5.2 2.3 virginica
146 147 6.3 2.5 5.0 1.9 virginica
147 148 6.5 3.0 5.2 2.0 virginica
148 149 6.2 3.4 5.4 2.3 virginica
149 150 5.9 3.0 5.1 1.8 virginica

150 rows × 6 columns

問題 3-4

iris ファイルを読み込んで、sepal length を横軸とし、petal length を縦軸とし、散布図を描け。ただし、iris のデータには setosa、versicolor、および virginica の 3 種のデータが含まれているので、これらを色で区別すること。

In [24]:
import pandas as pd
file_path = 'iris.txt'
df = pd.read_csv(file_path, sep='\t', comment='#', header=0)

sp = df.loc[:, 'Species']

df1 = df.loc[(sp == 'setosa'), :]
x1 = df1.loc[:, 'Sepal.Length']
y1 = df1.loc[:, 'Petal.Length']

df2 = df.loc[(sp == 'versicolor'), :]
x2 = df2.loc[:, 'Sepal.Length']
y2 = df2.loc[:, 'Petal.Length']

df3 = df.loc[(sp == 'virginica'), :]
x3 = df3.loc[:, 'Sepal.Length']
y3 = df3.loc[:, 'Petal.Length']

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x1, y1, label='setosa')
ax.scatter(x2, y2, label='versicolor')
ax.scatter(x3, y3, label='virginica')
ax.legend()
plt.show()
In [25]:
import pandas as pd
file_path = 'iris.txt'
df = pd.read_csv(file_path, sep='\t', comment='#', header=0)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

species = ['setosa', 'versicolor', 'virginica']
for sp in species:
    df1 = df.loc[(df.loc[:, 'Species'] == sp), :]
    x = df1.loc[:, 'Sepal.Length']
    y = df1.loc[:, 'Petal.Length']
    ax.scatter(x, y, label=sp)

ax.legend()
plt.show()

問題 3-5

setosa, versicolor, virginica の 3 種の sepal length および petal length の平均値を求めよ。

In [26]:
import pandas as pd
file_path = 'iris.txt'
df = pd.read_csv(file_path, sep='\t', comment='#', header=0)
sp = df.loc[:, 'Species']
df1 = df.loc[(sp == 'setosa'), :]
x1 = df1.loc[:, 'Sepal.Length']
y1 = df1.loc[:, 'Petal.Length']
x1_ave = np.mean(x1)
y1_ave = np.mean(y1)
print(x1_ave)
print(y1_ave)

df2 = df.loc[(sp == 'versicolor'), :]
x2 = df2.loc[:, 'Sepal.Length']
y2 = df2.loc[:, 'Petal.Length']
x2_ave = np.mean(x2)
y2_ave = np.mean(y2)
print(x2_ave)
print(y2_ave)

df3 = df.loc[(sp == 'virginica'), :]
x3 = df3.loc[:, 'Sepal.Length']
y3 = df3.loc[:, 'Petal.Length']
x3_ave = np.mean(x3)
y3_ave = np.mean(y3)
print(x3_ave)
print(y3_ave)
5.005999999999999
1.4620000000000002
5.936
4.26
6.587999999999998
5.552

問題 3-6

sleep_in_mammals.txt ファイルを読み込んで、LifeSpan をもっともよく説明するための特徴量(BodyWt, BrainWt, NonDreaming など LifeSpan 以外の列)を調べよ。ただし、特徴 A をよく説明できる特徴量を B とすると、特徴量 A と特徴量 B の相関係数が高いことが知られている。

In [27]:
file_path = 'sleep_in_mammals.txt'
df = pd.read_csv(file_path, comment='#', sep='\t', header=0)
df_corr = df.corr()
df_corr
Out[27]:
BodyWt BrainWt NonDreaming Dreaming TotalSleep LifeSpan Gestation Predation Exposure Danger
BodyWt 1.000000 0.934164 -0.375946 -0.109383 -0.307186 0.302451 0.651102 0.059495 0.338274 0.133581
BrainWt 0.934164 1.000000 -0.369218 -0.105139 -0.358102 0.509253 0.747242 0.033855 0.367800 0.145879
NonDreaming -0.375946 -0.369218 1.000000 0.514254 0.962715 -0.384432 -0.594703 -0.318185 -0.543757 -0.483852
Dreaming -0.109383 -0.105139 0.514254 1.000000 0.727087 -0.295745 -0.450899 -0.447471 -0.537225 -0.579337
TotalSleep -0.307186 -0.358102 0.962715 0.727087 1.000000 -0.410202 -0.631326 -0.395835 -0.642285 -0.587742
LifeSpan 0.302451 0.509253 -0.384432 -0.295745 -0.410202 1.000000 0.614849 -0.102544 0.360352 0.061778
Gestation 0.651102 0.747242 -0.594703 -0.450899 -0.631326 0.614849 1.000000 0.200504 0.638279 0.378617
Predation 0.059495 0.033855 -0.318185 -0.447471 -0.395835 -0.102544 0.200504 1.000000 0.618246 0.916042
Exposure 0.338274 0.367800 -0.543757 -0.537225 -0.642285 0.360352 0.638279 0.618246 1.000000 0.787203
Danger 0.133581 0.145879 -0.483852 -0.579337 -0.587742 0.061778 0.378617 0.916042 0.787203 1.000000

問題 3-7

sleep_in_mammals.txt ファイルを読み込んで、LifeSpan をもっともよく説明するための特徴量(BodyWt, BrainWt, NonDreaming など LifeSpan 以外の列)を 3 つ挙げよ。次に、この 3 つの特徴量と LifeSpan のデータのみを取り出して、train_data.txt ファイルに保存せよ。

In [28]:
file_path = 'sleep_in_mammals.txt'
df = pd.read_csv(file_path, comment='#', sep='\t', header=0)
# df_corr = df.corr()
# df_corr.loc[:, 'LifeSpan']

target_column = ['LifeSpan', 'BrainWt', 'Gestation', 'TotalSleep']
df_sub = df.loc[:, target_column]

df_sub.to_csv('new_file.txt')

問題 3-8

rice.txt データを読み込み、系統(variety 列:wt, ANU843)と処理群(fert 列:F10, NH4Cl, NH4NO3)の組み合わせごとの平均 root_dry_mass と shoot_dry_mass を求めよ。

系統 処理群 平均 root_dry_mass 平均 shoot_dry_mass
wt F10 ? ?
wt NH4Cl ? ?
wt NH4NO3 ? ?
ANU843 F10 ? ?
ANU843 NH4Cl ? ?
ANU843 NH4NO3 ? ?
In [29]:
file_path = 'rice.txt'
df = pd.read_csv(file_path, comment='#', sep='\t', header=0)

fert = df.loc[:, 'fert']
variety = df.loc[:, 'variety']

for v in ['wt', 'ANU843']:
    for f in ['F10', 'NH4Cl', 'NH4NO3']:
        df_sub = df.loc[variety == v, :].loc[fert == f, :]
        root_dry_mass_ave = df_sub.loc[:, 'root_dry_mass'].mean()
        shoot_dry_mass_ave = df_sub.loc[:, 'shoot_dry_mass'].mean()
        print(v, f, root_dry_mass_ave, shoot_dry_mass_ave)
wt F10 49.5 108.33333333333333
wt NH4Cl 12.583333333333334 50.25
wt NH4NO3 17.333333333333332 73.33333333333333
ANU843 F10 6.0 7.333333333333333
ANU843 NH4Cl 9.166666666666666 46.583333333333336
ANU843 NH4NO3 13.833333333333334 71.5