高度な形状変更 - 3 次元配列の作成
では、3 次元配列を作成することで、より高度な形状変更に移りましょう。3 次元配列は基本的に 2 次元配列の配列であり、ボリューム、画像の時系列、またはその他の複雑なデータ構造を表すのに役立ちます。
numpy_reshape.py ファイルに次のコードを追加します。
import numpy as np
## Create a simple 1D array
original_array = np.arange(24)
print("Original 1D array:")
print(original_array)
print("Shape of the original array:", original_array.shape)
print("-" * 50) ## Separator line
## Reshape into a 3D array with dimensions 2x3x4
## This creates 2 blocks, each with 3 rows and 4 columns
reshaped_3d = np.reshape(original_array, (2, 3, 4))
print("Reshaped 3D array (2x3x4):")
print(reshaped_3d)
print("Shape of the 3D array:", reshaped_3d.shape)
print("Dimensions of the 3D array:", reshaped_3d.ndim)
print("-" * 50) ## Separator line
## Accessing elements in a 3D array
print("First block of the 3D array:")
print(reshaped_3d[0])
print("\nSecond block of the 3D array:")
print(reshaped_3d[1])
print("\nElement at position [1,2,3] (second block, third row, fourth column):")
print(reshaped_3d[1, 2, 3])
再度スクリプトを実行します。
python3 numpy_reshape.py
出力では、24 個の要素を持つ 1 次元配列がどのように 3 次元構造に変換されるかが示されます。この構造は、それぞれが 3×4 の行列を含む 2 つの「ブロック」として視覚化することができます。
3 次元配列の理解:
- 最初の次元 (2) は、「ブロック」または「レイヤー」の数を表します。
- 2 番目の次元 (3) は、各ブロック内の行数を表します。
- 3 番目の次元 (4) は、各行内の列数を表します。
この構造は、画像処理(各「ブロック」が色チャネルである場合)、時系列データ(各「ブロック」が時点である場合)、または複数の行列を必要とするその他のシナリオで特に有用です。