【初心者向け】Numpyの関数その3(演算と判定)
データ分析において、NumPyはPythonの強力な武器です。NumPyが提供する配列操作は、効率的なデータ処理に不可欠な要素です。
この記事では、NumPy配列の演算と判定に焦点を当て、データ分析の基礎を固めます。
NumPy配列の演算
ユニバーサルファンクション: 配列の要素ごとに演算を適用
Pythonのリストで絶対値を求めたいと思ったら、次元分ループが必要です。
# Pythonのリストで絶対値を求める場合
bl = [[-3, -2, -1],[0, 1, 2]]
new = []
for i, row in enumerate(bl): # リストの1行目、2行目とループ
new.append([]) # リストnewの行を追加
for num in row: # リストの1列目、2列目、3列目とループ
new[i].append(abs(num))
new
[[3, 2, 1], [0, 1, 2]]
しかしNumpyではユニバーサルファンクションという便利な機能があり、ndarrayが一発で変換できます。
# データの準備
import numpy as np
a = np.arange(3)
b = np.arange(-3,3).reshape((2,3))
c = np.arange(1, 7).reshape((2,3))
d = np.arange(6).reshape((3,2))
e = np.linspace(-1, 1, 10)
print(a)
print(b)
print(c)
print(d)
print(e)
[0 1 2]
[[-3 -2 -1]
[ 0 1 2]]
[[1 2 3]
[4 5 6]]
[[0 1]
[2 3]
[4 5]]
[-1. -0.77777778 -0.55555556 -0.33333333 -0.11111111 0.11111111
0.33333333 0.55555556 0.77777778 1. ]
# ユニバーサルファンクションで絶対値
np.abs(b)
array([[3, 2, 1],
[0, 1, 2]])
他にも様々な関数があります。
np.sin(a),np.cos(a),np.tan(a)
(array([0. , 0.84147098, 0.90929743]),
array([ 1. , 0.54030231, -0.41614684]),
array([ 0. , 1.55740772, -2.18503986]))
np.log(c),np.log10(c),np.exp(c)
(array([[0. , 0.69314718, 1.09861229],
[1.38629436, 1.60943791, 1.79175947]]),
array([[0. , 0.30103 , 0.47712125],
[0.60205999, 0.69897 , 0.77815125]]),
array([[ 2.71828183, 7.3890561 , 20.08553692],
[ 54.59815003, 148.4131591 , 403.42879349]]))
ブロードキャスト: 形状が異なる配列間の演算
# ブロードキャスト
a + 10
array([10, 11, 12])
b + c
array([[-2, 0, 2],
[ 4, 6, 8]])
a + b # bの1行目にも2行目にもaが足されている
array([[-3, -1, 1],
[ 0, 2, 4]])
f = np.arange(3).reshape(1,3).T
print(f)
a + f
[[0]
[1]
[2]]
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
# 行列の積
np.dot(b, c) #左の行列の列と右の行列の行の数が合わないので計算できない
ValueError Traceback (most recent call last)
Cell In[445], line 1
----> 1 np.dot(b, c)
ValueError: shapes (2,3) and (2,3) not aligned: 3 (dim 1) != 2 (dim 0)
np.dot(c, d) # 行列の積
array([[16, 22],
[34, 49]])
c @ d # 行列の積(上と同じ)
array([[16, 22],
[34, 49]])
NumPy配列の判定・真偽値
# 真偽値
b > 0
array([[False, False, False],
[False, True, True]])
# bool値を整数に変換。Falseは0、Trueは0以外(1)
(b>0).astype(int)
array([[0, 0, 0],
[0, 1, 1]])
count_nonzero(): 0でない要素の数をカウント
np.count_nonzero(b>0)
2
any(): 少なくとも1つの要素がTrueかどうかを判定
np.any(b>0)
True
all(): すべての要素がTrueかどうかを判定
np.all(b>0)
False
allclose(): 2つの配列が近いかどうかを判定
b,c
(array([[-3, -2, -1],
[ 0, 1, 2]]),
array([[1, 2, 3],
[4, 5, 6]]))
np.allclose(b, c)
False
np.allclose(b, c, atol=4) #誤差が4以内か
True
np.allclose(b, c, atol=3) #誤差が3以内か
False
Discussion