多維陣列簡介、建立
## NumPy 多維陣列 `ndarray` 概念
`ndarray`(N-dimensional array)是 NumPy 的核心資料結構,用來儲存**固定資料型別、具備相同維度結構**的數值資料。
例如:
```python
import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6]
])
```
這是一個 2 維陣列,可視為 2 列 3 欄的表格。
常見屬性:
```python
a.ndim # 維度數:2
a.shape # 形狀:(2, 3)
a.size # 元素總數:6
a.dtype # 資料型別,例如 int64
```
### `ndarray` 的主要特色
- 支援 0 維、1 維、2 維甚至更高維度。
- 陣列中的元素通常具有相同的 `dtype`。
- 可進行向量化運算,不必逐一撰寫迴圈。
- 支援切片、索引、廣播(broadcasting)與矩陣運算。
- 通常比 Python `list` 更適合大量數值計算。
---
## 建立 `ndarray` 的常見方式
先匯入 NumPy:
```python
import numpy as np
```
### 1. 從 Python list 或 tuple 建立
```python
a = np.array([1, 2, 3])
b = np.array([
[1, 2],
[3, 4]
])
```
也可以指定資料型別:
```python
a = np.array([1, 2, 3], dtype=float)
```
---
### 2. 建立全為 0、1 或指定值的陣列
```python
np.zeros((2, 3)) # 2×3,全為 0
np.ones((2, 3)) # 2×3,全為 1
np.full((2, 3), 7) # 2×3,全為 7
```
結果例如:
```python
np.full((2, 3), 7)
# [[7, 7, 7],
# [7, 7, 7]]
```
`np.empty()` 也可建立指定形狀的陣列,但內容是未初始化值,不應直接當作 0 使用:
```python
np.empty((2, 3))
```
---
### 3. 建立連續數值
```python
np.arange(0, 10, 2)
# [0, 2, 4, 6, 8]
```
`arange(start, stop, step)` 類似 Python 的 `range`。
若想產生指定數量、平均分布的數值,可使用:
```python
np.linspace(0, 1, 5)
# [0. 0.25 0.5 0.75 1. ]
```
---
### 4. 建立單位矩陣或對角矩陣
```python
np.eye(3)
```
結果:
```text
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
```
---
### 5. 建立隨機陣列
```python
np.random.rand(2, 3) # 0 到 1 之間的均勻分布亂數
np.random.randn(2, 3) # 標準常態分布亂數
np.random.randint(1, 10, 5) # 產生 5 個 1~9 的整數
```
若希望結果可重現:
```python
np.random.seed(42)
```
---
### 6. 由現有陣列改變形狀
```python
a = np.arange(12)
b = a.reshape(3, 4)
```
`b` 會變成 3 列 4 欄:
```text
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
```
`reshape` 前後元素總數必須相同。
---
## 實務範例 1:計算多位學生的平均成績
假設每一列代表一位學生,每一欄代表一科成績:
```python
import numpy as np
scores = np.array([
[80, 75, 90],
[65, 88, 70],
[92, 95, 89]
])
# 每位學生的平均分數
student_avg = scores.mean(axis=1)
# 每一科的平均分數
subject_avg = scores.mean(axis=0)
print("每位學生平均:", student_avg)
print("每科平均:", subject_avg)
```
輸出概念:
```text
每位學生平均:[81.66666667 74.33333333 92. ]
每科平均:[79. 86. 83. ]
```
其中:
- `axis=1`:沿著欄方向計算,因此得到每一列的平均。
- `axis=0`:沿著列方向計算,因此得到每一欄的平均。
---
## 實務範例 2:影像像素的標準化
灰階影像可表示成 2 維陣列,每個元素是像素值,通常範圍為 0~255。以下將像素值轉換到 0~1:
```python
import numpy as np
image = np.array([
[0, 128, 255],
[64, 192, 32]
], dtype=np.float32)
normalized_image = image / 255.0
print(normalized_image)
```
結果約為:
```text
[[0. 0.5019608 1. ]
[0.2509804 0.7529412 0.1254902]]
```
這種處理常見於:
- 機器學習模型輸入資料前處理
- 影像亮度分析
- 將不同尺度的數值轉換到一致範圍
總結而言,建立 `ndarray` 最常見的方式包括 `np.array()`、`zeros()`、`ones()`、`full()`、`arange()`、`linspace()`、隨機函式,以及透過 `reshape()` 重新組織現有資料。
相關學習地圖、教學課程
Python 資料工程