1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

⚛️ NumPy チートシート

Posted at

📦 インポート

import numpy as np

📐 配列の作成

np.array([1, 2, 3])              # 1次元配列
np.array([[1, 2], [3, 4]])       # 2次元配列

np.zeros((3, 3))                 # 0で埋めた配列
np.ones((2, 4))                  # 1で埋めた配列
np.eye(3)                        # 単位行列
np.full((2, 3), 7)               # 指定値で埋める

np.arange(0, 10, 2)              # 0〜10未満を2刻みで
np.linspace(0, 1, 5)             # 0〜1を5分割

📏 配列の情報確認

arr.shape        # 形状(行×列)
arr.ndim         # 次元数
arr.size         # 要素数
arr.dtype        # データ型

🔁 形状変更・操作

arr.reshape(2, 3)       # 形を変える(要素数は一致)
arr.flatten()           # 1次元に平坦化
arr.T                   # 転置(行列の入れ替え)

np.concatenate([a, b])              # 配列の結合(1次元)
np.concatenate([a, b], axis=1)      # 横方向に結合(2次元)
np.stack([a, b], axis=0)            # 新しい次元で結合

🧮 基本演算

arr + 10               # 要素ごとの加算
arr * 2                # 要素ごとの乗算
np.sqrt(arr)           # 平方根
np.exp(arr)            # 指数関数
np.log(arr)            # 自然対数

np.sum(arr)            # 合計
np.mean(arr)           # 平均
np.std(arr)            # 標準偏差
np.max(arr), np.min(arr)  # 最大・最小
np.argmin(arr)         # 最小値のインデックス

🎯 条件演算・フィルタリング

arr > 5                        # 条件判定(ブール配列)
arr[arr > 5]                   # 条件に合う値だけ抽出
np.where(arr > 5, 1, 0)        # 条件で値を分岐(if的)

🔢 行列演算(線形代数)

np.dot(a, b)                  # ドット積
a @ b                         # ドット積(Python 3.5以降)
np.linalg.inv(a)             # 逆行列
np.linalg.det(a)             # 行列式
np.linalg.eig(a)             # 固有値と固有ベクトル

📚 おまけTips

操作 コマンド
データ型変換 arr.astype(np.float32)
ランダム生成 np.random.rand(3, 3)
シード固定 np.random.seed(42)
並び替え np.sort(arr)

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?