Cris 的 Python 資料分析筆記 03:NumPy 矩陣運算和常用函式(重點)
阿新 • • 發佈:2018-11-19
03. 矩陣運算和常用函式(重點)
文章目錄
1. numpy 矩陣判斷和計算
1.1 與運算
import numpy as np
# numpy 中對 ndarray 資料型別的與運算,對矩陣中的每一個元素都執行兩次判斷
data = np.array([1,2,3,4, 5])
result = (data == 1) & (data == 3)
print(result)
[False False False False False]
1.2 或運算
# 矩陣的或運算,對矩陣中的每一個元素都執行判斷,只要滿足其中一個條件就返回True
data = np.array([1,2,3,4,5])
result = (data == 1)| (data == 3)
print(result)
[ True False True False False]
1.3 或運算作為矩陣索引賦值
'''
可以將或運算判斷後的結果作為索引重新為矩陣賦值,對應位置的判斷結果為True,則賦值;否則保持原元素
'''
data = np.array([1,2,3,4,2])
index = (data == 1) | (data == 2)
data[index] = 10
print(data)
[10 10 3 4 10]
1.4 或運算為二維矩陣賦值
'''
先判斷所有行的第二列是否包含 2 ,返回 bool 資料型別的列表,然後將這個列表作為二維矩陣的行引數,為
列表中所有為 True 的行的第三列賦值為 111
'''
matrix = np.array([[1,2,3],[1,4,2],[2,1,5]])
index = matrix[:,1] == 2
print(index)
matrix[index,2] = 111
print(matrix)
[ True False False]
[[ 1 2 111]
[ 1 4 2]
[ 2 1 5]]
1.5 astype 改變元素資料型別
'''
astype 可以對矩陣中的元素統一進行資料型別的轉換
'''
data = np.array(['1','23','33'])
print (data.dtype)
data = data.astype(float)
print(data.dtype)
print(data)
<U2
float64
[ 1. 23. 33.]
1.6 極值函式
# 求最小值
data = np.array([1,23,44,-3])
print(data.min())
-3
1.7 axis 指定維度求和
'''
axis 為 1 表示對每行求和,返回一個列表;axis 為 0 表示對每列求和,同樣返回列表
'''
matrix = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(matrix.sum(axis=1))
print(matrix.sum(axis=0))
[ 6 15 24]
[12 15 18]
1.8 符號計算
'''
對於相同維度的矩陣,- 表示對應位置的元素相減
矩陣直接 - 數字,表示對該矩陣的每一個元素都執行 - 數字的操作
** 表示乘方運算
矩陣 < 數字 or 矩陣 > 數字 可以對矩陣中的每個元素進行判斷,返回列表或者是二維列表
矩陣 * 矩陣 表示對應位置的元素進行乘法計算
矩陣a.dot(矩陣b) 表示 a 的每一行元素和 b 的每一列元素對應位置相乘求和然後放入新的結果矩陣中/可以使用 np.dot(a,b) 代替
'''
a = np.array([11,22,33,44])
b = np.arange(4)
c = a - b
print(c)
c = c -1
print(c)
print(b**2)
print(b)
print(b < 2)
a = np.array([[1,2],[3,4]])
b = np.array([[0,1],[1,2]])
print(a*b)
print(a.dot(b))
print(np.dot(a,b))
[11 21 31 41]
[10 20 30 40]
[0 1 4 9]
[0 1 2 3]
[ True True False False]
[[0 2]
[3 8]]
[[ 2 5]
[ 4 11]]
[[ 2 5]
[ 4 11]]
2. numpy 常用函式(重點)
2.1 reshape 函式快速重構二維矩陣
'''
arange 函式快速生成一維的有序的矩陣,可通過 reshape 方法對一維矩陣快速變換為二維矩陣,第一個引數表示行
第二個引數表示列,shape 屬性可以檢視當前二維矩陣的維度資訊(行列資訊),ndim 屬性表示維度,二維矩陣就是2
dtype 屬性表示每個元素的資料型別,size 表示總共有多少個元素
'''
data = np.arange(15)
print(data)
data = data.reshape(3,5)
print(data)
# (3,5)
data.shape
# 2
data.ndim
# 'int32'
data.dtype.name
# dtype('int32')
data.dtype
data.size
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
15
2.2 矩陣的初始化
# 根據元祖初始化所有元素都是 0. 的二維矩陣(預設是 float 型別)
data = np.zeros((2,3))
data
# 構造一個所有元素都是 1 的三維矩陣,並可以指定元素的型別為 int
# 第一個引數表示三維矩陣的元素個數,第二個引數表示二維矩陣的元素個數,第三個引數表示一維矩陣的元素個數
data = np.ones((2,3,4),dtype=np.int32)
data
array([[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]],
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]])
2.3 快速生成序列
# 從 10-40,每隔 5 取一個數生成序列,滿足前包後不包
data = np.arange(10,40,5)
data
array([10, 15, 20, 25, 30, 35])
2.4 random 生成隨機值
# 生成二維矩陣型別隨機值的函式,需要一個元祖引數,第一個引數表示行,第二個引數表示列,隨機值預設 [0.0,1.0)
'''
array([[0.39091032, 0.94434359, 0.09856153],
[0.32999742, 0.30763014, 0.23284478]])
'''
np.random.random((2,3))
help(np.random.random)
Help on built-in function random_sample:
random_sample(...) method of mtrand.RandomState instance
random_sample(size=None)
Return random floats in the half-open interval [0.0, 1.0).
Results are from the "continuous uniform" distribution over the
stated interval. To sample :math:`Unif[a, b), b > a` multiply
the output of `random_sample` by `(b-a)` and add `a`::
(b - a) * random_sample() + a
Parameters
----------
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. Default is None, in which case a
single value is returned.
Returns
-------
out : float or ndarray of floats
Array of random floats of shape `size` (unless ``size=None``, in which
case a single float is returned).
Examples
--------
>>> np.random.random_sample()
0.47108547995356098
>>> type(np.random.random_sample())
<type 'float'>
>>> np.random.random_sample((5,))
array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428])
Three-by-two array of random numbers from [-5, 0):
>>> 5 * np.random.random_sample((3, 2)) - 5
array([[-3.99149989, -0.52338984],
[-2.99091858, -0.79479508],
[-1.23204345, -1.75224494]])
2.5 指定區間取平均間隔的值
# 從指定區間根據 區間長度/元素個數 得到的均值為取值間隔來取值, pi 表示 圓周率派
np.linspace(0,2*pi,5)
array([0. , 1.57079633, 3.14159265, 4.71238898, 6.28318531])
2.6 求 e 的冪和陣列所有元素的平方根
number = np.arange(5)
print(number)
print(np.exp(number))
print(np.sqrt(number))
[0 1 2 3 4]
[ 1. 2.71828183 7.3890561 20.08553692 54.59815003]
[0. 1. 1.41421356 1.73205081 2. ]
2.7 矩陣變換
# 隨機生成兩行三列的 0-1 之間的隨機數
nums = np.random.random((2,3))
print(nums)
# floor 函式用於向下取整
nums = np.floor(10*nums)
print(nums)
# ravel 函式用於 flatten the array
nums = np.ravel(nums)
print(nums)
# shape 函式用於重新變換矩陣結構,第一個引數都是行,第二個引數都是列
nums.shape = (3,2)
print(nums)
# 完成矩陣的行列轉置(原矩陣每一行作為新矩陣的每一列)
print(nums.T)
# reshape 函式自動根據第一個行引數計算列引數,傳入 -1 就可以自動計算
print(nums.reshape(6,-1))
print(nums)
[[0.34773665 0.22488604 0.95113666]
[0.56553515 0.64450662 0.92665817]]
[[3. 2. 9.]
[5. 6. 9.]]
[3. 2. 9. 5. 6. 9.]
[[3. 2.]
[9. 5.]
[6. 9.]]
[[3. 9. 6.]
[2. 5. 9.]]
[[3.]
[2.]
[9.]
[5.]
[6.]
[9.]]
[[3. 2.]
[9. 5.]
[6. 9.]]
2.8 矩陣之間的拼接
# hstack 函式用於矩陣之間根據每行來拼接,增加列(特徵)
# vstack 函式用於矩陣之間根據每列來拼接,增加行
# 不管是橫拼還是豎拼,注意拼接時的維度數量要一致
a = np.floor(10*np.random.random((2,2)))
b = np.floor(10*np.random.random((2,2)))
print(a)
print('---------------')
print(b)
print(np.hstack((a,b)))
print(np.vstack((a,b)))
[[6. 5.]
[8. 6.]]
---------------
[[8. 2.]
[9. 6.]]
[[6. 5. 8. 2.]
[8. 6. 9. 6.]]
[[6. 5.]
[8. 6.]
[8. 2.]
[9. 6.]]
2.9 矩陣切分
'''
hsplit(矩陣,x):x 表示對矩陣的每行按列切割為幾份;如果 x 為元祖,表示按照元祖指定的索引進行自定義切分
vsplit(矩陣,y):y 表示對矩陣的每行按行切割為幾份
'''
nums = np.floor(10*np.random.random((2,6)))
print(nums)
print(np.hsplit(nums,3))
nums = np.floor(10*np.random.random((2,6)))
print(nums)
print(np.hsplit(nums,(3,4)))
print('---------------')
nums = nums.T
print(nums)
print(np.vsplit(nums,2))
[[6. 4. 5. 7. 2. 2.]
[8. 2. 8. 2. 1. 8.]]
[array([[6., 4.],
[8., 2.]]), array([[5., 7.],
[8., 2.]]), array([[2., 2.],
[1., 8.]])]
[[5. 8. 5. 6. 3. 6.]
[5. 2. 1. 0. 9. 1.]]
[array([[5., 8., 5.],
[5., 2., 1.]]), array([[6.],
[0.]]), array([[3., 6.],
[9., 1.]])]
---------------
[[5. 5.]
[8. 2.]
[5. 1.]
[6. 0.]
[3. 9.]
[6. 1.]]
[array([[5., 5.],
[8., 2.],
[5., 1.]]), array([[6., 0.],
[3., 9.],
[6., 1.]])]