1.

NumPy 配列の作成方法完全ガイド

編集
この記事の要点
  • np.array([1, 2, 3]) が最も基本的な配列生成
  • ゼロ・1・等差数列: np.zeros / np.ones / np.arange / np.linspace
  • 単位行列は np.eye(n)、定数充填は np.full
  • dtype 指定で型を制御 (int32 / float64 / bool / complex)
  • reshape(rows, cols) で次元変換、メモリは C-order がデフォルト

基本: np.array()

Python リスト / タプルから NumPy 配列 (ndarray) を生成する最も基本的な関数:

import numpy as np

# 1 次元配列
a = np.array([1, 2, 3, 4, 5])
print(a)         # [1 2 3 4 5]
print(a.shape)   # (5,)
print(a.dtype)   # int64

# 2 次元配列
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b)
# [[1 2 3]
#  [4 5 6]]
print(b.shape)   # (2, 3)
print(b.ndim)    # 2

# 3 次元配列
c = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(c.shape)   # (2, 2, 2)

定数充填: zeros / ones / full / empty

# すべて 0 で埋める
zeros = np.zeros((3, 4))
# [[0. 0. 0. 0.]
#  [0. 0. 0. 0.]
#  [0. 0. 0. 0.]]
# dtype はデフォルト float64

# すべて 1 で埋める
ones = np.ones((2, 3), dtype=np.int32)
# [[1 1 1]
#  [1 1 1]]

# 任意の値で埋める
sevens = np.full((2, 2), 7)
# [[7 7]
#  [7 7]]

# 未初期化(高速だが値はランダム)
empty = np.empty((1000, 1000))
# 後で全要素を上書きするときに使う

# 既存配列と同じ shape で
ref = np.array([[1, 2], [3, 4]])
zeros_like = np.zeros_like(ref)    # shape=(2,2), dtype=int
ones_like = np.ones_like(ref, dtype=float)
full_like = np.full_like(ref, fill_value=99)

数列: arange / linspace

# Python の range() の NumPy 版
a = np.arange(10)           # [0 1 2 3 4 5 6 7 8 9]
b = np.arange(2, 10)        # [2 3 4 5 6 7 8 9]
c = np.arange(0, 10, 2)     # [0 2 4 6 8]
d = np.arange(0, 1, 0.1)    # [0. 0.1 0.2 ... 0.9]  ※浮動小数では誤差注意

# 区間を等分(端点を含む点数指定)
e = np.linspace(0, 1, 11)
# [0.  0.1 0.2 0.3 ... 1.0]  ← 11 個

# 対数スケール
f = np.logspace(0, 3, 4)
# [   1.   10.  100. 1000.]

arange と linspace の使い分け:

arangelinspace
引数start, stop, stepstart, stop, num
stop の扱い含まない含む(endpoint=True デフォルト)
浮動小数精度誤差累積あり正確に分割
用途整数系浮動小数の等分

単位行列: eye / identity

# 単位行列(対角が 1、他は 0)
I = np.eye(3)
# [[1. 0. 0.]
#  [0. 1. 0.]
#  [0. 0. 1.]]

# 長方形行列も可能
I = np.eye(3, 5)
# [[1. 0. 0. 0. 0.]
#  [0. 1. 0. 0. 0.]
#  [0. 0. 1. 0. 0.]]

# 対角をずらす
I = np.eye(4, k=1)   # 1 つ右上
# [[0. 1. 0. 0.]
#  [0. 0. 1. 0.]
#  [0. 0. 0. 1.]
#  [0. 0. 0. 0.]]

# identity は eye の正方行列版
I = np.identity(4)

dtype(データ型)の指定

dtypeバイト数範囲・用途
int81-128 〜 127
int162-32768 〜 32767
int324±21 億
int648デフォルト整数
uint810-255 (画像によく使う)
float162半精度(機械学習)
float324単精度(GPU で標準)
float648デフォルト浮動小数
bool1True / False
complex64 / 1288 / 16複素数
# dtype を明示
a = np.array([1, 2, 3], dtype=np.float32)
b = np.zeros(10, dtype=np.uint8)            # 画像処理向け
c = np.array([True, False, True], dtype=bool)
d = np.array([1+2j, 3-4j], dtype=complex)

# 型変換
a_int = a.astype(np.int32)
# astype は新しい配列を返す(元は変更されない)

# 文字列も可能(固定長)
s = np.array(['abc', 'defgh'], dtype='U10')   # Unicode 最大 10 文字

reshape: 次元変換

# 0-11 の 1 次元配列を 3×4 行列に
a = np.arange(12).reshape(3, 4)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

# -1 は自動計算
b = np.arange(12).reshape(2, -1)
# 自動で 6 → shape (2, 6)

c = np.arange(24).reshape(2, 3, 4)   # 3D
# shape = (2, 3, 4)

# 1 次元に戻す
d = c.reshape(-1)
# shape = (24,)

ndarray のメモリレイアウト

NumPy 配列は内部的には連続メモリ上の 1 次元バイト列です。多次元はストライド(次元ごとのバイト跨ぎ)で表現します:

a = np.arange(12).reshape(3, 4)

print(a.shape)       # (3, 4)
print(a.strides)     # (32, 8)
# 32: 行を 1 進めるのに 32 バイト(int64 × 4 列)
# 8:  列を 1 進めるのに 8 バイト

# C-order(行優先、デフォルト)
b = np.arange(12).reshape(3, 4, order='C')
print(b.flags.c_contiguous)   # True

# F-order(列優先、Fortran 互換)
c = np.arange(12).reshape(3, 4, order='F')
print(c.flags.f_contiguous)   # True

# メモリ消費
print(a.nbytes)    # 96 (12 * 8 bytes)
print(a.itemsize)  # 8

乱数からの生成

# 新 API(推奨、NumPy 1.17+)
rng = np.random.default_rng(seed=42)

a = rng.random((3, 4))                # [0, 1) の一様分布
b = rng.integers(0, 10, size=(2, 5))  # [0, 10) の整数
c = rng.normal(0, 1, size=100)        # 標準正規分布
d = rng.choice([1, 2, 3], size=10)    # サンプリング

# 旧 API(非推奨だが現役)
np.random.seed(42)
e = np.random.rand(3, 4)
f = np.random.randint(0, 10, (2, 5))

FAQ

Q: 大きな配列を作るのにメモリ不足
A: np.emptynp.memmap(ディスクマップ)を使う。dtype を float64 → float32 にすれば半分のサイズに。

Q: np.array([1, "a"]) の dtype は
A: 異なる型が混ざると共通の型に昇格。文字列と数値混在では 等になる。

Q: copy と view の違いは
A: reshape や slice は view(同じメモリを共有)、copy()flatten() はコピー。

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. 配列の作成
  2. 多次元配列の作成
  3. 要素の参照
  4. 要素の追加
  5. 要素の更新
  6. 要素の削除
  7. ブロードキャスト
  8. 多次元配列の構造の確認
  9. 多次元配列を1次元配列に変換
  10. 1次元配列を多次元配列に変換
  11. 要素の範囲指定
  12. 平均値の算出
  13. 行列を結合する方法