NumpyはPythonの数値計算用ライブラリです。Numpyを使用することで、行列計算を高速に行うことができます。
任意の1次元配列を作成
import numpy as np data = [1, 2, 3, 4] arr = np.array(data) print(arr) #[1 2 3 4] print(type(arr)) #<class 'numpy.ndarray'> print(arr.shape) #(4,)
任意の2次元配列を作成
import numpy as np data = [[1, 2, 3, 4], [5, 6, 7, 8]] arr = np.array(data) print(arr) #[[1 2 3 4] # [5 6 7 8]] print(arr.shape) #(2, 4)
要素がすべて0の配列を作成
import numpy as np arr = np.zeros(10) print(arr) #[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] print(arr.shape) #(10,) arr = np.zeros((3, 4)) print(arr) #[[0. 0. 0. 0.] # [0. 0. 0. 0.] # [0. 0. 0. 0.]] print(arr.shape) #(3, 4)
要素がすべて1の配列を作成
import numpy as np arr = np.ones(10) print(arr) #[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] print(arr.shape) #(10,) arr = np.ones((3, 4)) print(arr) #[[1. 1. 1. 1.] # [1. 1. 1. 1.] # [1. 1. 1. 1.]] print(arr.shape) #(3, 4)
連続した数字の配列を作成
import numpy as np arr1 = np.arange(10) print(arr1) #[0 1 2 3 4 5 6 7 8 9] print(arr1.shape) #(10,) arr2 = np.arange(5, 10) print(arr2) #[5 6 7 8 9] print(arr2.shape) #(5,) arr3 = np.arange(2, 10, 2) print(arr3) #[2 4 6 8] print(arr3.shape) #(4,)
基本的な計算
import numpy as np data1 = [[1, 2], [3, 4]] arr1 = np.array(data1) data2 = [[0, 1], [2, 3]] arr2 = np.array(data2) print(arr1) #[[1 2] # [3 4]] print(arr1.shape) #(2, 2) print(arr2) #[[0 1] # [2 3]] print(arr2.shape) #(2, 2) print(arr1 * arr2) #[[ 0 2] # [ 6 12]] print(arr1 - arr2) #[[1 1] # [1 1]] print(arr2 / arr1) #[[0. 0.5 ] # [0.66666667 0.75 ]] print(arr1 ** 2) #[[ 1 4] # [ 9 16]] print(arr1 > arr2) #[[ True True] # [ True True]]