配列の作成
配列の作成
1. 学習内容
- ❶ Pythonオブジェクトからの作成
- ❷ 数列 (arange / linspace / logspace)
- ❸ あらかじめ値が設定された配列(ゼロ/1/アイ/フル)
- ❹ 乱数生成
- ❺ ファイルからの読み込み
2. ストーリー
チャーリーは、0から2πまでの範囲で、等間隔に配置された100個の角度を必要としています。Pythonのループ:5行。np.linspace:1行。
linspace(0, 2*pi, 100)は「0 から 2π までの範囲から、等間隔で 100 個の点を抽出する」という意味です。コードこそがドキュメントです。
3. 主要な概念
(1) Pythonオブジェクトからの作成
最も基本的なアプローチ――Pythonのリスト(またはネストされたリスト)をNumPy配列に変換する方法:
import numpy as np
a = np.array([1, 2, 3]) # 1D from list
b = np.array([[1, 2], [3, 4]]) # 2D from nested list
c = np.array([1, 2, 3], dtype=float) # specify dtype
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
作成方法の比較
| メソッド | 構文 | 入力元 | 代表的な用途 |
|---|---|---|---|
np.array |
np.array(obj) |
Pythonのリスト/タプル | 既存データの変換 |
np.arange |
np.arange(start, stop, step) |
数値範囲 | 整数/浮動小数点数のシーケンス |
np.linspace |
np.linspace(a, b, n) |
開始、停止、カウント | 正確な要素数のカウント |
np.zeros |
np.zeros(shape) |
形状 | すべてゼロに初期化 |
np.ones |
np.ones(shape) |
形状 | すべて「1」に初期化 |
np.full |
np.full(shape, val) |
形状+塗りつぶし値 | 任意の値に初期化 |
np.random.rand |
np.random.rand(n) |
要素数 | ランダム初期化 |
np.fromfunction |
np.fromfunction(fn, shape) |
機能+形状 | 数式による生成 |
(2) 数列
arange
np.arange(5) # [0 1 2 3 4]
np.arange(1, 10, 2) # [1 3 5 7 9]
np.arange(0, 1, 0.3) # [0. 0.3 0.6 0.9]
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
linspace
np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1. ]
np.linspace(0, 2*np.pi, 100) # 100 points from 0 to 2pi
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
logspace
np.logspace(1, 3, 3) # [ 10. 100. 1000.] -- 10^1, 10^2, 10^3
np.logspace(0, 2, 5) # 5 points from 10^0 to 10^2
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
arange 対 linspace 対 logspace
| 特集 | arange |
linspace |
logspace |
|---|---|---|---|
| 制御 | 開始、停止、ステップ | 開始、停止、num | start_exp、stop_exp、num |
| ストップを含む | いいえ | はい | はい |
| 間隔 | 線形 | 線形 | 対数 |
| 浮動小数点精度 | 誤差が生じる可能性がある | 正確 | 正確 |
| 代表的な用途 | 整数インデックス | サンプルのプロット | 周波数/対数スケール |
(3) 事前初期化済み配列
np.zeros(3) # [0. 0. 0.]
np.zeros((2, 3)) # 2x3 zero matrix
np.ones((2, 2)) # 2x2 ones
np.eye(3) # 3x3 identity
np.full((2, 3), 7) # 2x3 filled with 7
np.empty((2, 2)) # 2x2 uninitialized (NOT zeros!)
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
ゼロ vs 空 vs 満杯
| 機能 | 初期値 | 速度 | 安全性 | 用途 |
|---|---|---|---|---|
zeros |
すべてゼロ | 中 | 安全 | 既知の初期値が必要 |
empty |
未定義 | 高速 | 安全でない | すべての要素を直ちに上書き |
full |
カスタム値 | 中 | 安全 | 0 以外の初期値が必要 |
(4) 乱数の生成
np.random.rand(3) # 3 uniform [0, 1)
np.random.rand(2, 3) # 2x3 uniform
np.random.randn(3) # 3 standard normal
np.random.randint(0, 10, 5) # 5 ints in [0, 10)
np.random.seed(42) # set seed for reproducibility
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
ランダム関数のクイックリファレンス
| 関数 | 分布 | 定義域 | 戻り値の型 |
|---|---|---|---|
rand(d0, d1, ...) |
均一 | [0, 1) | float |
randn(d0, d1, ...) |
標準正規分布 | (-∞, +∞) | float |
randint(low, high, size) |
一様な整数 | [low, high) | int |
uniform(low, high, size) |
均一 | [low, high) | float |
normal(loc, scale, size) |
通常 | (-∞, +∞) | float |
choice(a, size) |
離散一様 | の要素 | に依存する |
(5) ファイルからの読み込み
data = np.loadtxt('data.txt') # plain text
data = np.loadtxt('data.csv', delimiter=',') # CSV
data = np.genfromtxt('data.csv', delimiter=',', # handle missing
filling_values=0)
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
fromfunction — 座標関数による配列の生成:
np.fromfunction(lambda i, j: i + j, (3, 3))
# [[0. 1. 2.]
# [1. 2. 3.]
# [2. 3. 4.]]
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(1) ▶ サンプル
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
: arange 対 linspace 対 logspace (難易度 ⭐)
import numpy as np
# arange: step-based
a = np.arange(0, 10, 2) # [0 2 4 6 8]
print("arange:", a)
# linspace: num-based
b = np.linspace(0, 10, 6) # 6 points: 0, 2, 4, 6, 8, 10
print("linspace:", b)
# logspace: logarithmic
c = np.logspace(1, 4, 4) # [10, 100, 1000, 10000]
print("logspace:", c)
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(2) ▶ サンプル
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
: ゼロ / ワン / アイ / フル (難易度 ⭐)
import numpy as np
z = np.zeros((2, 3))
print("zeros:\n", z)
o = np.ones((3, 2))
print("ones:\n", o)
e = np.eye(4)
print("eye:\n", e)
f = np.full((2, 3), 9.0)
print("full:\n", f)
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(3) ▶ サンプル
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
: ネストされたリストを2次元配列に変換する(難易度 ⭐)
import numpy as np
data = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
a = np.array(data)
print("shape:", a.shape) # (3, 3)
print("dtype:", a.dtype) # int64
print("ndim:", a.ndim) # 2
print("array:\n", a)
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(4) ▶ サンプル
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
: ランダムな配列の生成 (難易度 ⭐)
import numpy as np
np.random.seed(42)
print("rand(3):", np.random.rand(3))
print("randn(3):", np.random.randn(3))
print("randint(0,10,5):", np.random.randint(0, 10, 5))
print("uniform(0,1,3):", np.random.uniform(0, 1, 3))
print("normal(0,1,3):", np.random.normal(0, 1, 3))
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
4. 比較表
(1) ユースケースに基づく作成方法
| 必要性 | 方法 | 理由 |
|---|---|---|
| 既存データの変換 | np.array(data) |
直接変換 |
| 整数の数列 | np.arange(n) |
軽量 |
| 正確なフローティングシーケンス | np.linspace(a, b, n) |
正確なカウント |
| 固定値行列 | np.full(shape, val) |
任意の埋め込み値 |
| 単位行列 | np.eye(n) |
線形代数 |
| ランダム初期化 | np.random.rand(...) |
ML重み |
| ファイルから読み込む | np.loadtxt(file) |
外部データ |
(2) arange と Python の range の比較
| 特集 | range |
np.arange |
|---|---|---|
| 戻り値 | 遅延イテレータ | ndarray (実体化済み) |
| メモリ | O(1) | O(n) |
| フロートステップ | いいえ | はい |
| 処理速度(反復処理) | 遅い | 速い(ベクトル化) |
| ユースケース | ループ処理 | 配列の作成 |
5. 原理図
graph TB
A[Python List] -->|np.array| B[ndarray]
C[arange / linspace] --> B
D[zeros / ones / eye] --> B
E[random functions] --> B
F[file: loadtxt] --> B
B --> G[uniform dtype]
B --> H[contiguous memory]
B --> I[vectorized ops]
❓ よくある質問
np.random.default_rng(seed) を使用して Generator オブジェクトを作成し、その後 .random()、.normal()、.integers() などを呼び出します。 従来の np.random.seed() も引き続き使用できますが、レガシーと見なされています。np.array(x for x in range(10)) は機能しません。ジェネレータオブジェクトを含む0次元配列が作成されてしまいます。代わりに np.fromiter((x for x in range(10)), dtype=int) を使用してください。np.genfromtxt('file.csv', delimiter=',', filling_values=0) を使用して欠損値をデフォルト値に置き換えるか、np.nan を使用してください。📖 まとめ
np.array()は Python のリストを ndarray に変換します。dtype は自動的に推論されます。arange(start, stop, step)は等間隔のシーケンスを生成し、linspaceはその数を制御しますzeros/ones/eye/fullは初期値が設定済みの配列を作成する;emptyは高速だが、初期化されていない- 乱数関数:
rand(一様分布)、randn(正規分布)、randint(整数)、choice(サンプリング) loadtxtおよびgenfromtxtはテキストファイルから配列を読み込みます。一方、fromfunctionは数式に基づいて生成します。
📝 練習問題
-
初心者向け(難易度 ⭐): 以下の配列を作成してください:(a) 0 から 9 までの整数、(b) 0 から 1 までの間に等間隔で配置された 10 個の点、(c) 3×3 の単位行列、(d) すべて 7 で構成される 2×4 の配列。
-
中級(難易度 ⭐⭐):
np.loadtxtを使用して、3つの列(名前(文字列)、年齢(整数)、給与(浮動小数点数))からなるCSVファイルを読み込みます。 混合型を処理するために、np.genfromtxtとdtype=Noneを組み合わせて使用してください。平均給与を出力してください。 -
上級 (難易度 ⭐⭐⭐):
np.random.rand(10_000_000)と Python のリスト内包表記を用いて、1,000 万個の乱数を生成するベンチマークを作成してください。所要時間とメモリ使用量の差を記録してください。次に、np.random.default_rng()を使用して、処理速度を比較してください。