# D03 Numpy 陣列的初始化

`numpy.array(object, dtype=None, *, copy=True, order=’K’, subok=False, ndmin=0, like=None)`

## 從內建型態做轉換

`np.array(list({0: 123, 1: 456}.items()))# array([[  0 123]  [  1 456]])`

## 從固定大小的初始值開始

`np.zeros((2, 3))# 建立由 0 組成的 2x3 陣列np.ones((2, 3))# 建立由 1 組成的 2x3 陣列np.full((2, 3), 9)# 建立由 9 組成的 2x3 陣列np.empty((2, 3))#zero vs. empty: 完全皆為零／極小的數`

## 從固定大小的序列值開始

`np.arange( 10, 30, 5 )# array([10, 15, 20, 25])np.linspace( 0, 2, 3 )# array([0. 1. 2.])np.logspace( 0, 2, 3 )# array([1. 10. 100.])`

## 從固定大小的亂數值開始

`from numpy.random import default_rngrng = default_rng()normal = rng.standard_normal((3,2))random = rng.random((3,2))integers = rng.integers(0, 10, size=(3,2))`

# D04 NumPy 陣列的算術運算

## 常數與陣列運算

`import numpy as npa = np.array( [20,30,40,50] )print(a - 2)# [18 28 38 48]print(a / 10)# [2. 3. 4. 5.]`

## 不同大小的陣列運算

`import numpy as npdata = np.array([[1, 2], [3, 4], [5, 6]])ones_row = np.array([[1, 1]])print(data + ones_row)# array([[2, 3],#        [4, 5],#        [6, 7]])`

## 陣列運算與容器運算的差異

`a = np.array( [20,30,40,50] )print(a + 1)# array([21 31 41 51]a = [20, 30, 40, 50]b = []for i in a:  b.append(i+1)print(b)# [21, 31, 41, 51]`

# D05 NumPy 陣列的邏輯、比較運算

## 陣列中的比較運算

`import numpy as npa = np.array( [20,30,40,50] )b = np.arange( 4 )print(a > b) # [ True  True  True  True]print(a < b) # [False False False False]print(a == b) # [False False False False]print(a != b) # [ True  True  True  True]`

## 陣列中的邏輯運算(and, or, not)

`import numpy as npa = np.array( [True, True, False, False] )b = np.array( [True, False, True, False]  )print(a and b)Traceback (most recent call last):  ...ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()`

## 利用布林值作為篩選的條件：遮罩

`import numpy as npa = np.array( [10, 20, 30, 40] )print(a[ [True, True, True, True] ])# [10 20 30 40]print(a[ [True, False, True, False] ])# [10 30]print(a[ [False, False, False, False] ])# []`

# D06 Numpy 中常見的陣列方法與函式

`np.sort(array)array.sort()`
`# 搜尋與排序方法np.searchsorted([1,2,3,4,5], 3)# 2`
`# 攤平import numpy as npa = np.arange(6).reshape((3, 2))print(a.ravel() )print(a.flatten())print(a.flat)`

# D07 NumPy 陣列的索引、切片和迭代

`import numpy as npdata = np.array([1, 2, 3])print(data[0]) # 取出第 0 個print(data[1]) # 取出第 1 個print(data[0:2]) # 第 0 - 1 個print(data[1:]) # 第 1 到最後一個print(data[-2:]) # 倒數第二到最後一個`