python科學計算-numpy

NumPy 是一個 Python 包。 它表明 「Numeric Python」。 它是一個由多維數組對象和用於處理數組的例程集合組成的庫。Numpy自己並無提供多麼高級的數據分析功能,理解 Numpuy 數組以及面向數組的計算將有助於你更加高效的使用諸如 pandas 之類的工具。python

import numpy as np

# 1.數組建立
a = [[1,2,3,4],[5,6,7,8]]
b = np.array(a)     #建立numpy數組
c = np.linspace(start=0,stop=2,num=100)
d = np.arange(0,10,0.2)
print(type(b))
print(b)

# 2.數組的屬性
print(b.size)   #元素個數
print(b.shape)  #形狀
print(b.ndim)   #維度
print(b.dtype)  #元素類型

# 3.數組的快速建立
# 3.1 N維0和1數組的建立
array_one = np.ones([10, 10])   #建立10行10列的數值爲浮點1的矩陣
array_zero = np.zeros([10, 10]) #建立10行10列的數值爲浮點0的矩陣

# 3.2 均勻分佈
r_01 = np.random.rand(10, 10)  #建立指定形狀(示例爲10行10列)的數組(範圍在0至1之間)
u_mn = np.random.uniform(0, 100)    #建立指定範圍內的一個數
ri_mn = np.random.randint(0, 100)   #建立指定範圍內的一個整數

# 3.3 正態分佈
n = np.random.normal(1.75, 0.1, (5, 5))   #給定均值/標準差/維度的正態分佈
n_02 = np.random.randn(5,5)
n_03 = np.random.normal(0,1,(5,5))  #n_02與n_03等價

# 3.4 序列數組
ar = np.arange(0,20,2)  #numpy中的arange與內置函數range類似
ls = np.linspace(0,10,21)   #建立等差序列數組,其參數依次爲:開始值、結束值、元素數量。

# 4.數組的索引和切片
n_arr = n[1:3,1:4]  #數組的下標從0開始,切片時包括左邊,但不包括右邊。


# 5.數組的計算
# 5.1 條件運算
score = np.array([[80, 88], [82, 81], [84, 75], [86, 83], [75, 81]])
TF = score > 80 #其結果是此前相同形狀的True和False數組
np.where(score>80,1,0)  #三目選擇運算

# 5.2統計運算
col_max = np.amax(score, axis=0)    #每一列的最大值爲
row_max = np.amax(score, axis=1)    #每一行的最大值爲

col_m = np.mean(score, axis=0)      #每一列的均值爲
row_m = np.mean(score, axis=1)      #每一行的均值爲

col_s = np.std(score, axis=0)      #每一列的標準差爲
row_s = np.std(score, axis=1)      #每一行的標準差爲

# 5.3矩陣運算 np.dot()
# (M行, N列) * (N行, Z列) = (M行, Z列)
a = np.ones([3,4])  #a是3行4列
b = np.ones([4,5])+1    #b是4行5列
c = np.dot(a,b)     #c是3行5列

# 5.4矩陣拼接
v1 = [[0, 1, 2, 3, 4, 5],
      [6, 7, 8, 9, 10, 11]]
v2 = [[12, 13, 14, 15, 16, 17],
      [18, 19, 20, 21, 22, 23]]

result_1 = np.vstack((v1, v2))    #垂直拼接
result_2 = np.hstack((v1, v2))    #水平拼接
相關文章
相關標籤/搜索