1. 程式人生 > >Python 學習筆記之 Numpy 庫——數組基礎

Python 學習筆記之 Numpy 庫——數組基礎

array oat dot tac 運算 stop ogr 數據類型 總數

1. 初識數組

import numpy as np
a = np.arange(15)
a = a.reshape(3, 5)
print(a.ndim, a.shape, a.dtype, a.size, a.itemsize)
# 2 (3, 5) int64 15 8
  • ndim,數組的維度數,二維數組就是 2
  • shape,數組在各個維度上的長度,用元組表示
  • dtype,數組中元素的數據類型,比如 int32, float64 等
  • size,數組中所有元素的總數
  • itemsize,數組中每個元素所占的字節數

2. 創建數組

a = np.array([[1, 2, 3], [4, 5, 6]])
a = np.ones((3, 4))
a = np.zeros((3, 4), dtype=np.float32)
a = np.linspace(0, 2, 9)   # 9 numbers from 0 to 2
  • np.linspace(start, stop, num=50) 產生一個區間在[start, stop],長度為 num 的一維數組

3. 基本運算

a = np.array([[1, 2, 3], [4, 5, 6]]) # (2, 3)
b = np.array([[1, 0, 1], [0, 1, 1], [1, 1, 0]]) # (3, 3)
c = np.dot(a, b)        # 矩陣相乘
d = a @ b                 # 矩陣相乘
e = np.dot(a[0], [0])   # 向量內積
f = a * a                   # 元素相乘

g = np.sum(a)
h = np.mean(a, axis=0)
  • np.sum 等函數若不指定 axis,則把數組所有元素當成列表來處理,axis = 0,表示只在第一個維度上進行求和,以此類推。

4. 維度操作

a = np.zeros((2, 3))
b = np.zeros((3, 3))
np.vstack((a, b)).shape # (5, 3)
  • np.vstack, 沿著垂直方向或者行的方向將數組堆起來
a = np.zeros((2, 1, 5))
b = np.zeros((2, 2, 5))
np.hstack((a, b)).shape # (2, 3, 5)
  • np.hstack, 沿著水平方向或者列的方向將數組堆起來
a = np.zeros((2, 5, 1))
b = np.zeros((2, 5, 5))
np.concatenate((a, b), axis=2).shape # (2, 5, 6)
  • np.concatenate, 沿著某一維度將數組堆起來
a = np.zeros((3, ))
b = np.zeros((3, ))
np.stack((a, b), axis=0).shape # (2, 3)
np.stack((a, b), axis=1).shape # (3, 2)
  • np.stack, 將數組沿著新的維度堆起來

5. 隨機數

a = np.random.rand(3, 2) # (3, 2)
  • np.random.rand, 返回一個 [0, 1) 之間的隨機分布
a = np.random.random((2, 3)) # (2, 3)
  • np.random.random, 返回一個 [0, 1) 之間的隨機分布
a = np.random.randn(3, 2) # (3, 2)
a = sigma * np.random.randn(...) + mu 
  • np.random.randn, 返回一個均值為 0 方差為 1 的標準正態分布,通過 mu 和 sigma 可以任意改變均值和方差
a = np.random.randint(1, 5, (3, 2)) # (3, 2)
  • np.random.randint(low, high=None, size=None), 返回一個 [0, low) 或者 [low, high) 之間的隨機整數
np.random.choice(np.arange(5, 10), 3, replace=False)
np.random.choice(5, (3,2))
  • np.random.choice(a, size=None, replace=True, p=None), 返回 a 中元素或者 np.arange(a) 範圍內的隨機整數,replace=True 默認可以有重復元素
np.random.seed(1)
a = np.random.rand(3, 2)
np.random.seed(1)
b = np.random.rand(3, 2) # a == b

a = np.array([1, 2, 3, 4, 5])
np.random.shuffle(a) 
  • np.random.seed 通過設置隨機數種子的值可以保證兩次產生的隨機數相同
  • np.random.shuffle() 沿著第一維隨機打亂數組

獲取更多精彩,請關註「seniusen」!
技術分享圖片

Python 學習筆記之 Numpy 庫——數組基礎