1
0

More than 3 years have passed since last update.

【100 numpy exercises】でnumpy力を鍛える!(31〜40問目)

Last updated at Posted at 2021-08-24

こんにちは!

前回はnumpy力を鍛えるために21~30問やっていきました。

前回の記事はこちら

それでは前回に引き続き100 numpy exercisesを使ってnumpyの学習をしていきたいと思います!

今回は31~40問をやっていきます。

31. How to ignore all numpy warnings (not recommended)? (★☆☆)

31. numpyの警告をすべて無視する方法(推奨しません)?
100_numpy_exercises.ipynb(31)
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0

np.seterrは浮動小数点エラーを処理します。上記のように本来ならエラーが発生するような演算があった場合も無視します。

100_numpy_exercises.ipynb(31)-output
#何も出力されない

32. Is the following expressions true? (★☆☆)

32. 次の表現は正しいですか?
100_numpy_exercises.ipynb(32)
np.sqrt(-1) == np.emath.sqrt(-1)

np.sqrtは引数が負の実数の場合にはnanを返します。
np.emath.sqrtは引数が負の実数にも、複素数を返します。

実行結果は以下の通りです。

100_numpy_exercises.ipynb(32)-output
False

33. How to get the dates of yesterday, today and tomorrow? (★☆☆)

33. 昨日、今日、明日の日付を知るには?
100_numpy_exercises.ipynb(33)
yesterday = np.datetime64('today') - np.timedelta64(1)
today     = np.datetime64('today')
tomorrow  = np.datetime64('today') + np.timedelta64(1)

np.datetime64の引数にtodayを入れることで今日の日付を得ることができます。
昨日、明日を知るには、np.datetime64を補完する関数であるnp.timedelta64を使うと日時の増減算ができます。

34. How to get all the dates corresponding to the month of July 2016? (★★☆)

34. 2016年7月の月に対応するすべての日付を取得するには?
100_numpy_exercises.ipynb(34)
Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
print(Z)

np.arangedtypedatetime64[D]を指定することで第一引数と第二引数間の全ての日付を指定することができます。

実行結果は以下の通りです。

100_numpy_exercises.ipynb(34)-output
['2016-07-01' '2016-07-02' '2016-07-03' '2016-07-04' '2016-07-05'
 '2016-07-06' '2016-07-07' '2016-07-08' '2016-07-09' '2016-07-10'
 '2016-07-11' '2016-07-12' '2016-07-13' '2016-07-14' '2016-07-15'
 '2016-07-16' '2016-07-17' '2016-07-18' '2016-07-19' '2016-07-20'
 '2016-07-21' '2016-07-22' '2016-07-23' '2016-07-24' '2016-07-25'
 '2016-07-26' '2016-07-27' '2016-07-28' '2016-07-29' '2016-07-30'
 '2016-07-31']

35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)

z35. ((A+B)*(-A/2))をその場で(コピーなしで)計算するには?(★★☆)
100_numpy_exercises.ipynb(35)
A = np.ones(3)*1
B = np.ones(3)*2
np.add(A,B,out=B)
np.divide(A,2,out=A)
np.negative(A,out=A)
np.multiply(A,B,out=A)

この問題の目的はnp.copyを使わずに演算するというものです。numpyは四則演算も可能です。
np.add,np.negative,np.multiply,np.divideという関数が用意されています。オプションにoutを指定して、結果が保存される場所を決めることができます。

実行結果は以下の通りです。

100_numpy_exercises.ipynb(35)-output
array([-1.5, -1.5, -1.5])

36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)

36. 正の数のランダムな配列の整数部分を4種類の方法で抽出する
100_numpy_exercises.ipynb(36)
Z = np.random.uniform(0,10,10)

print(Z - Z%1)
print(Z // 1)
print(np.floor(Z))
print(Z.astype(int))
print(np.trunc(Z))

1つ目は%で余りの配列が求まるので、それを元の配列から引けば整数部分だけを抽出できます。
2つ目は整数徐算で小数点が切り捨てなので抽出できます。
3つ目のnp.floorは小数点以下の切り捨てができる関数です。
4つ目はintにデータ型の変換をすることによって整数を抽出しています。
5つ目はnp.truncで0への丸めを行い整数を抽出しています。

実行結果は以下の通りです。

100_numpy_exercises.ipynb(36)-output
[0. 2. 1. 3. 9. 6. 5. 9. 1. 5.]
[0. 2. 1. 3. 9. 6. 5. 9. 1. 5.]
[0. 2. 1. 3. 9. 6. 5. 9. 1. 5.]
[0 2 1 3 9 6 5 9 1 5]
[0. 2. 1. 3. 9. 6. 5. 9. 1. 5.]

37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)

37. 行の値が0から4までの5x5の行列を作る
100_numpy_exercises.ipynb(37)
Z = np.tile(np.arange(0, 5), (5,1))
print(Z)

np.tileを使いnp.arangeで指定した範囲の配列を繰り返し並べることによって行列を作ることができます。

実行結果は以下の通りです。

100_numpy_exercises.ipynb(37)-output
[[0 1 2 3 4]
 [0 1 2 3 4]
 [0 1 2 3 4]
 [0 1 2 3 4]
 [0 1 2 3 4]]

38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)

38. 10個の整数を生成するgenerate関数を考え、それを使って配列を構築する
100_numpy_exercises.ipynb(38)
def generate():
    for x in range(10):
        yield x
Z = np.fromiter(generate(),dtype=float,count=-1)
print(Z)

np.fromiterは反復可能なオブジェクトから一次元配列を作成します。

実行結果は以下の通りです。

100_numpy_exercises.ipynb(38)-output
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]

39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)

39. 0から1までの値を持つが、0も1も要素に持たないサイズ10のベクトルを作成する
100_numpy_exercises.ipynb(39)
Z = np.linspace(0,1,11,endpoint=False)[1:]
print(Z)

np.linspaceは線形に等間隔な数列を生成することができる関数です。オプションにendpointを指定し、その値をFalseにすることによって第三引数に指定した値を含まないことを表しています。endpointを11に指定することで11番目の要素が1になるが、これを配列に含まないようにします。最後に配列の1番目よりあとを選ぶことで0を含まない配列になります。

実行結果は以下の通りです。

100_numpy_exercises.ipynb(39)-output
[0.09090909 0.18181818 0.27272727 0.36363636 0.45454545 0.54545455
 0.63636364 0.72727273 0.81818182 0.90909091]

40. Create a random vector of size 10 and sort it (★★☆)

40. サイズ10のランダムなベクトルを作り、それをソートする
100_numpy_exercises.ipynb(40)
Z = np.random.random(10)
Z.sort()
print(Z)

生成した配列に対してsortを使うことによって昇順に並びます。降順にしたい場合は、[::-1]を使うと降順に並びます。

実行結果は以下の通りです。

100_numpy_exercises.ipynb(40)-output
[8.71018950e-04 1.93628619e-01 3.71699714e-01 4.13487510e-01
 4.76347522e-01 5.71809350e-01 6.33744758e-01 7.10447741e-01
 7.52859539e-01 8.98640149e-01]

今回は以上になります。
次回は41~50問をやっていきます。

次回の記事はこちら

1
0
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
1
0