NumPy

NumPy 基本計算まとめ

スカラー演算、平方根・累乗

x = np.array([0, 1, 2, 3, 4, 5], dtype = np.float)

print(x) # [0. 1. 2. 3. 4. 5.]
print(x + 1) # [1. 2. 3. 4. 5. 6.]
print(x - 1) # [-1.  0.  1.  2.  3.  4.]
print(x * 2) # [ 0.  2.  4.  6.  8. 10.]
print(x / 2) # [0.  0.5 1.  1.5 2.  2.5]
print(x // 2) # [0. 0. 1. 1. 2. 2.]
print(x % 2) # [0. 1. 0. 1. 0. 1.]

print(np.sqrt(x)) # [0.         1.         1.41421356 1.73205081 2.         2.23606798]
print(np.power(x, 2)) # [ 0.  1.  4.  9. 16. 25.]
print(x ** 2) # [ 0.  1.  4.  9. 16. 25.]

四捨五入, 切り捨て, 切り上げ, 整数に

import numpy as np
x = np.array([-1.5, -1.25, -1., -0.5, -0.2, 0., 0.25, 0.5, 1., 1.25, 1.5],
             dtype = np.float)

# 四捨五入
print(np.round(x)) # [-2. -1. -1. -0. -0.  0.  0.  0.  1.  1.  2.]
print(np.around(x)) # [-2. -1. -1. -0. -0.  0.  0.  0.  1.  1.  2.]
print(np.rint(x)) # [-2. -1. -1. -0. -0.  0.  0.  0.  1.  1.  2.]

# 値が小さい方の整数に切り捨て
print(np.floor(x)) # [-2. -2. -1. -1. -1.  0.  0.  0.  1.  1.  1.]

# 小数部分を切り捨て
print(np.trunc(x)) # [-1. -1. -1. -0. -0.  0.  0.  0.  1.  1.  1.]

# 値が大きい方の整数に
print(np.ceil(x)) # [-1. -1. -1. -0. -0.  0.  1.  1.  1.  2.  2.]

# 0に近い方の整数に
print(np.fix(x)) # [-1. -1. -1. -0. -0.  0.  0.  0.  1.  1.  1.]

三角関数

import numpy as np
x = np.array([0, 1], dtype = np.float)

print(np.sin(x)) # [ 0.         0.84147098 ]
print(np.cos(x)) # [ 1.         0.54030231 ]
print(np.tan(x)) # [ 0.         1.55740772 ]

# 逆関数
print(np.arcsin(np.sin(x))) # [0. 1.]
print(np.arccos(np.cos(x))) # [0. 1.]
print(np.arctan(np.tan(x))) # [0. 1.]

ラジアンと角度、相互変換

import numpy as np

x = np.array([0, 90, 180, 270, 360], dtype = np.float)

print(np.radians(x)) # [0.         1.57079633 3.14159265 4.71238898 6.28318531]
print(np.deg2rad(x)) # [0.         1.57079633 3.14159265 4.71238898 6.28318531]
print(np.rad2deg(np.deg2rad(x))) # [  0.  90. 180. 270. 360.]

最大、最小、平均、分散、標準偏差、不偏分散、不偏標準偏差

import numpy as np
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype = np.float)

# 最大
print(np.max(x)) # 10.0
# 最小
print(np.min(x)) # 0.0
#平均
print(np.mean(x)) # 5.0

# 分散
print(np.var(x)) # 10.0
# 標準偏差
print(np.std(x)) # 3.1622776601683795

# 不偏分散
print(np.var(x, ddof=1)) # 11.0

# 不偏標準偏差
print(np.std(x, ddof=1)) # 3.3166247903554