NumPy(ナンパイ)とは?
Pythonで 高速な数値計算 を行うためのライブラリです。
科学技術計算・機械学習・データ分析の分野では、ほぼ必須の基盤的なツールです。
🔹 できることの概要
| 分野 | 例 |
|---|---|
| 配列(ベクトル・行列)計算 | 例:足し算・掛け算などを高速に実行 |
| 統計処理 | 平均・分散・標準偏差など |
| 線形代数 | 行列積・逆行列・固有値分解など |
| 乱数生成 | ランダムな数列や行列を生成 |
| 配列操作 | スライス・結合・分割・転置など |
⚙️ NumPyの中核:ndarray
NumPyの中心的なデータ構造は ndarray(N次元配列) です。
Pythonのリストよりも メモリ効率が良く、高速 に動作します。
test.py
import numpy as np
# 1次元配列(ベクトル)
a = np.array([1, 2, 3, 4, 5])
# 2次元配列(行列)
b = np.array([[1, 2, 3],
[4, 5, 6]])
print(a)
print(b)
(venv) kerumatomomitsu@kerumatomomitsunoMacBook-Air stock_portfolio % python test.py
[1 2 3 4 5]
[[1 2 3]
[4 5 6]]
🧩 配列の基本情報
test.py
import numpy as np
# 1次元配列(ベクトル)
a = np.array([1, 2, 3, 4, 5])
# 2次元配列(行列)
b = np.array([[1, 2, 3], [4, 5, 6]])
print("次元数:", b.ndim) # 2
print("形状:", b.shape) # (2, 3)
print("要素数:", b.size) # 6
print("データ型:", b.dtype) # int64など
(venv) kerumatomomitsu@kerumatomomitsunoMacBook-Air stock_portfolio % python test.py
次元数: 2
形状: (2, 3)
要素数: 6
データ型: int64
➕ 要素ごとの演算
NumPyは「ベクトル化演算」を行えるのが大きな特徴です。
Pythonのfor文より圧倒的に速いです。
test.py
import numpy as np
a = np.array([1, 2, 3])
print(a + 10) # [11 12 13]
print(a * 2) # [2 4 6]
print(a**2) # [1 4 9]
(venv) kerumatomomitsu@kerumatomomitsunoMacBook-Air stock_portfolio % python test.py
[11 12 13]
[2 4 6]
[1 4 9]
🧮 ブロードキャスト機能
test.py
import numpy as np
b = np.array([[1, 2, 3], [4, 5, 6]])
c = np.array([[10], [20]])
print(b + c)
(venv) kerumatomomitsu@kerumatomomitsunoMacBook-Air stock_portfolio % python test.py
[[11 12 13]
[24 25 26]]
📊 統計処理も簡単!
test.py
import numpy as np
b = np.array([[1, 2, 3], [4, 5, 6]])
print("平均:", np.mean(b))
print("最大値:", np.max(b))
print("最小値:", np.min(b))
print("標準偏差:", np.std(b))
(venv) kerumatomomitsu@kerumatomomitsunoMacBook-Air stock_portfolio % python test.py
平均: 3.5
最大値: 6
最小値: 1
標準偏差: 1.707825127659933
🎲 乱数の生成
test.py
import numpy as np
np.random.seed(0)
rand_arr = np.random.rand(3, 3) # 0〜1の乱数
print(rand_arr)
(venv) kerumatomomitsu@kerumatomomitsunoMacBook-Air stock_portfolio % python test.py
[[0.5488135 0.71518937 0.60276338]
[0.54488318 0.4236548 0.64589411]
[0.43758721 0.891773 0.96366276]]
🧠 線形代数(行列計算)
test.py
x = np.array([[1, 2],
[3, 4]])
y = np.array([[5, 6],
[7, 8]])
print("行列積:", x @ y)
print("転置:", x.T)
print("逆行列:", np.linalg.inv(x))
(venv) kerumatomomitsu@kerumatomomitsunoMacBook-Air stock_portfolio % python test.py
行列積: [[19 22]
[43 50]]
転置: [[1 3]
[2 4]]
逆行列: [[-2. 1. ]
[ 1.5 -0.5]]
📈 Pythonリストとの違い
| 項目 | Pythonのリスト | NumPy配列 |
|---|---|---|
| 速度 | 遅い(for文処理) | 速い(C言語実装) |
| メモリ効率 | 高くない | 高い |
| ベクトル演算 | 不可 | 可能 |
| 次元操作 | 難しい | 容易 |
🧩 応用例(科学計算やAI分野)
• 機械学習(TensorFlow, PyTorchなどの基礎)
• 画像処理(OpenCV, PIL)
• データ分析(Pandasの内部はNumPyベース)
• シミュレーション、統計解析