初心者のためのpython入門

自分がつまづいたところやつまづきやすいところを中心に書いていきます。また、役に立つライブラリの紹介などをしていきます。

Numpy[3]

前書き

今回は、Numpyの続きについて説明します。

行列

前回までの説明で使用していた多次元配列は、行列とほとんど同じ演算などが行えますが厳密な意味で行列ではありません。Numpyで明示的に行列を扱いたい場合は、matrixを用います。

  • np.matrix(list or tuple): 引数に与えられたものを行列へと変換します。
>>> import numpy as np # numpyのインポート
>>> A = np.matrix([[1, 2], [3, 4]])
>>> B = np.matrix([[5, 6], [7, 8]])
>>> A * B # 行列の積
matrix([[19, 22],
        [43, 50]])
>>> C = np.array([[1, 2], [3, 4]])
>>> D = np.array([[5, 6], [7, 8]])
>>> C * D # 要素ごとの積
array([[ 5, 12],
       [21, 32]])

スライス

ndarrayは、スライスで要素を取り出すことができます。

>>> A = np.arange(12).reshape(2, 2, 3)
>>> A
array([[[ 0,  1,  2],
        [ 3,  4,  5]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])
>>> A[:, 1, :] # =  A[0:2, 1, 0:3]
array([[ 3,  4,  5],
       [ 9, 10, 11]])
>>> A[0, 1, :]
array([3, 4, 5])
>>> A[0, 1, 2]
5

数学関数

  • 三角関数
    • np.sin(radian): サインの値を計算する。
    • np.cos(radian): コサインの値を計算する。
    • np.tan(radian): タンジェントの値を計算する。
  • 三角関数
    • np.arcsin(): アークサインの値を計算し、radianで返す。
    • np.arccos(): アークコサインの値を計算し、radianで返す。
    • np.arctan(): アークタンジェントの値を計算し、radianで返す。
  • 定数π
    • np.pi: 円周率を示す定数。
# sin 
>>> np.sin(0)
0.0

# arccos
>>> np.arccos(0.5)
1.0471975511965976

# tan
>>> np.tan(np.pi)
-1.2246467991473532e-16
# 度からラジアン
>>> np.deg2rad(60)
1.0471975511965976

# ラジアンから度
>>> np.rad2deg(3.14)
179.90874767107849
  • 指数と対数
    • np.exp(x): ネイピア数(e)を底とする指数関数。
    • np.log2(x): 底が2の対数関数。
    • np.log10(x): 底が10の対数関数。
    • np.log1p(x): 底がネイピア数の(1+x)を計算する対数関数。
# 1乗
>>> np.exp(1)
2.7182818284590451

# 2乗
>>> np.exp(2)
7.3890560989306504

>>> np.log2(8)
3.0
>>> np.log10(2)
0.3010299956639812

# loge(e)と同じ
>>> np.log1p(np.exp(1) - 1)
1.0
  • 絶対値
    • np.abs(x): 複素数の絶対値を扱える。
    • np.fabs(x): 複素数の絶対値を扱えない。
# 複素数を扱える
>>> np.abs(-2 + 1j)
2.2360679774997898

# 複素数を扱えない
>>> np.fabs(-2 + 1j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ufunc 'fabs' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
  • 切り上げ・切り捨て・四捨五入
    • np.floor(x): 値が小さくなるよう切り捨て。
    • np.trunc(x): 小数部分を切り捨て。
    • np.ceil(x): 値が大きくなるように切り上げ。
    • np.round(x): 四捨五入。np.around()も同じ。
    • np.fix(x): 小数を0に近くなるように整数にする。
>>> x = np.array([-1.2, -1.6, 1.3, 1.8])

# 切り捨て
>>> np.floor(x)
array([-2., -2.,  1.,  1.])

# 切り捨て
>>> np.trunc(x)
array([-1., -1.,  1.,  1.])

# 切り上げ
>>> np.ceil(x)
array([-1., -1.,  2.,  2.])

# 四捨五入
>>> np.round(x)
array([-1., -2.,  1.,  2.])

# 0に近くなるように整数へ
>>> np.fix(x)
array([-1., -1.,  1.,  1.])

あとがき

お疲れ様でした。今回説明した以外にもNumpyにはたくさんの機能があるので、必要になったら調べてみましょう。また、matplotlibの説明をする予定でしたが、Numpyが思ったより長くなってしまったので次回にします。