一、用于資料分析、科學計算與可視化的擴展模塊主要有:numpy、scipy、pandas、SymPy、matplotlib、Traits、TraitsUI、Chaco、TVTK、Mayavi、VPython、OpenCV,
1.numpy模塊:科學計算包,支持N維陣列運算、處理大型矩陣、成熟的廣播函式庫、矢量運算、線性代數、傅里葉變換、亂數生成、并可與C++ /Fortran語言無縫結合,Python v3默認安裝已經包含了numpy,
(1)匯入模塊:import numpy as np















切片操作
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a[::-1] # 反向切片
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
>>> a[::2] # 隔一個取一個元素
array([0, 2, 4, 6, 8])
>>> a[:5] # 前5個元素
array([0, 1, 2, 3, 4])
>>> c = np.arange(25) # 創建陣列
>>> c.shape = 5,5 # 修改陣列大小
>>> c
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
>>> c[0, 2:5] # 第0行中下標[2,5)之間的元素值
array([2, 3, 4])
>>> c[1] # 第0行所有元素
array([5, 6, 7, 8, 9])
>>> c[2:5, 2:5] # 行下標和列下標都介于[2,5)之間的元素值
array([[12, 13, 14],
[17, 18, 19],
[22, 23, 24]])
布爾運算
>>> x = np.random.rand(10) # 包含10個亂數的陣列
>>> x
array([ 0.56707504, 0.07527513, 0.0149213 , 0.49157657, 0.75404095,
0.40330683, 0.90158037, 0.36465894, 0.37620859, 0.62250594])
>>> x > 0.5 # 比較陣列中每個元素值是否大于0.5
array([ True, False, False, False, True, False, True, False, False, True], dtype=bool)
>>> x[x>0.5] # 獲取陣列中大于0.5的元素,可用于檢測和過濾例外值
array([ 0.56707504, 0.75404095, 0.90158037, 0.62250594])
>>> x < 0.5
array([False, True, True, True, False, True, False, True, True, False], dtype=bool)
>>> np.all(x<1) # 測驗是否全部元素都小于1
True
>>> np.any([1,2,3,4]) # 是否存在等價于True的元素
True
>>> np.any([0])
False
>>> a = np.array([1, 2, 3])
>>> b = np.array([3, 2, 1])
>>> a > b # 兩個陣列中對應位置上的元素比較
array([False, False, True], dtype=bool)
>>> a[a>b]
array([3])
>>> a == b
array([False, True, False], dtype=bool)
>>> a[a==b]
array([2])
取整運算
>>> x = np.random.rand(10)*50 # 10個亂數
>>> x
array([ 43.85639765, 30.47354735, 43.68965984, 38.92963767,
9.20056878, 21.34765863, 4.61037809, 17.99941701,
19.70232038, 30.05059154])
>>> np.int64(x) # 取整
array([43, 30, 43, 38, 9, 21, 4, 17, 19, 30], dtype=int64)
>>> np.int32(x)
array([43, 30, 43, 38, 9, 21, 4, 17, 19, 30])
>>> np.int16(x)
array([43, 30, 43, 38, 9, 21, 4, 17, 19, 30], dtype=int16)
>>> np.int8(x)
array([43, 30, 43, 38, 9, 21, 4, 17, 19, 30], dtype=int8)
廣播
>>> a = np.arange(0,60,10).reshape(-1,1) # 列向量
>>> b = np.arange(0,6) # 行向量
>>> a
array([[ 0],
[10],
[20],
[30],
[40],
[50]])
>>> b
array([0, 1, 2, 3, 4, 5])
>>> a[0] + b # 陣列與標量的加法
array([0, 1, 2, 3, 4, 5])
>>> a[1] + b
array([10, 11, 12, 13, 14, 15])
>>> a + b
array([[ 0, 1, 2, 3, 4, 5],
[10, 11, 12, 13, 14, 15],
[20, 21, 22, 23, 24, 25],
[30, 31, 32, 33, 34, 35],
[40, 41, 42, 43, 44, 45],
[50, 51, 52, 53, 54, 55]])
>>> a * b
array([[ 0, 0, 0, 0, 0, 0],
[ 0, 10, 20, 30, 40, 50],
[ 0, 20, 40, 60, 80, 100],
[ 0, 30, 60, 90, 120, 150],
[ 0, 40, 80, 120, 160, 200],
[ 0, 50, 100, 150, 200, 250]])
分段函式
>>> x = np.random.randint(0, 10, size=(1,10))
>>> x
array([[0, 4, 3, 3, 8, 4, 7, 3, 1, 7]])
>>> np.where(x<5, 0, 1) # 小于5的元素值對應0,其他對應1
array([[0, 0, 0, 0, 1, 0, 1, 0, 0, 1]])
>>> np.piecewise(x, [x<4, x>7], [lambda x:x*2, lambda x:x*3])
# 小于4的元素乘以2
# 大于7的元素乘以3
# 其他元素變為0
array([[ 0, 0, 6, 6, 24, 0, 0, 6, 2, 0]])
計算唯一值以及出現次數
>>> x = np.random.randint(0, 10, 7)
>>> x
array([8, 7, 7, 5, 3, 8, 0])
>>> np.bincount(x) # 元素出現次數,0出現1次,
# 1、2沒出現,3出現1次,以此類推
array([1, 0, 0, 1, 0, 1, 0, 2, 2], dtype=int64)
>>> np.sum(_) # 所有元素出現次數之和等于陣列長度
7
>>> np.unique(x) # 回傳唯一元素值
array([0, 3, 5, 7, 8])
矩陣運算
>>> a_list = [3, 5, 7]
>>> a_mat = np.matrix(a_list) # 創建矩陣
>>> a_mat
matrix([[3, 5, 7]])
>>> a_mat.T # 矩陣轉置
matrix([[3],
[5],
[7]])
>>> a_mat.shape # 矩陣形狀
(1, 3)
>>> a_mat.size # 元素個數
3
>>> a_mat.mean() # 元素平均值
5.0
>>> a_mat.sum() # 所有元素之和
15
>>> a_mat.max() # 最大值
7
>>> a_mat.max(axis=1) # 橫向最大值
matrix([[7]])
>>> a_mat.max(axis=0) # 縱向最大值
matrix([[3, 5, 7]])
>>> b_mat = np.matrix((1, 2, 3)) # 創建矩陣
>>> b_mat
matrix([[1, 2, 3]])
>>> a_mat * b_mat.T # 矩陣相乘
matrix([[34]])
>>> c_mat = np.matrix([[1, 5, 3], [2, 9, 6]]) # 創建二維矩陣
>>> c_mat
matrix([[1, 5, 3],
[2, 9, 6]])
>>> c_mat.argsort(axis=0) # 縱向排序后的元素序號
matrix([[0, 0, 0],
[1, 1, 1]], dtype=int64)
>>> c_mat.argsort(axis=1) # 橫向排序后的元素序號
matrix([[0, 2, 1],
[0, 2, 1]], dtype=int64)
>>> d_mat = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> d_mat.diagonal() # 矩陣對角線元素
matrix([[1, 5, 9]])
矩陣不同維度上的計算
>>> x = np.matrix(np.arange(0,10).reshape(2,5)) # 二維矩陣
>>> x
matrix([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> x.sum() # 所有元素之和
45
>>> x.sum(axis=0) # 縱向求和
matrix([[ 5, 7, 9, 11, 13]])
>>> x.sum(axis=1) # 橫向求和
matrix([[10],
[35]])
>>> x.mean() # 平均值
4.5
>>> x.mean(axis=1)
matrix([[ 2.],
[ 7.]])
>>> x.mean(axis=0)
matrix([[ 2.5, 3.5, 4.5, 5.5, 6.5]])
>>> x.max() # 所有元素最大值
9
>>> x.max(axis=0) # 縱向最大值
matrix([[5, 6, 7, 8, 9]])
>>> x.max(axis=1) # 橫向最大值
matrix([[4],
[9]])
>>> weight = [0.3, 0.7] # 權重
>>> np.average(x, axis=0, weights=weight)
matrix([[ 3.5, 4.5, 5.5, 6.5, 7.5]])
>>> x = np.matrix(np.random.randint(0, 10, size=(3,3)))
>>> x
matrix([[3, 7, 4],
[5, 1, 8],
[2, 7, 0]])
>>> x.std() # 標準差
2.6851213274654606
>>> x.std(axis=1) # 橫向標準差
matrix([[ 1.69967317],
[ 2.86744176],
[ 2.94392029]])
>>> x.std(axis=0) # 縱向標準差
matrix([[ 1.24721913, 2.82842712, 3.26598632]])
>>> x.var(axis=0) # 縱向方差
matrix([[ 1.55555556, 8. , 10.66666667]])
2.matplotlib模塊:依賴于numpy模塊和tkinter模塊,可以繪制多種形式的圖形,包括線圖、直方圖、餅狀圖、散點圖、誤差線圖等等,圖形質量可滿足出版要求,是資料可視化的重要工具,
二、使用numpy、matplotlib模塊繪制雷達圖
import numpy as np
import matplotlib.pyplot as plt
# 中文和負號的正常顯示
plt.rcParams['font.sans-serif'] = 'Microsoft YaHei'
plt.rcParams['axes.unicode_minus'] = False
# 使用ggplot的繪圖風格
plt.style.use('ggplot')
# 構造資料
values = [5,5,5,5,5,5,5]
feature = ['第一周','第二周','第三周','第四周','第五周','第六周','第七周']
N = len(values)
# 設定雷達圖的角度,用于平分切開一個圓面
angles=np.linspace(0, 2*np.pi, N, endpoint=False)
# 為了使雷達圖一圈封閉起來,需要下面的步驟
values=np.concatenate((values,[values[0]]))
angles=np.concatenate((angles,[angles[0]]))
# 繪圖
fig=plt.figure()
ax = fig.add_subplot(111, polar=True)
# 繪制折線圖
ax.plot(angles, values, 'o-', linewidth=2, label = '學號2019310143016')
# 填充顏色
ax.fill(angles, values, alpha=0.35)
# 添加每個特征的標簽
ax.set_thetagrids(angles * 180/np.pi, feature)
# 設定雷達圖的范圍
ax.set_ylim(0,5)
# 添加標題
plt.title('純牛奶的成績單')
# 添加網格線
ax.grid(True)
# 設定圖例
plt.legend(loc = 'best')
# 顯示圖形
plt.show()

三、使用PIL、numpy模塊繪制自定義手繪風
from PIL import Image
import numpy as np
a = np.asarray(Image.open("xiaoxiao.jpg").convert("L")).astype("float")
depth = 50
grad = np.gradient(a)
grad_x, grad_y = grad
grad_x = grad_x*depth/100
grad_y = grad_y*depth/100
A = np.sqrt(grad_x**2 + grad_y**2 + 1.)
uni_x = grad_x/A
uni_y = grad_y/A
uni_z = 1./A
vec_el = np.pi/2.2
vec_az = np.pi/4.
dx = np.cos(vec_el)*np.cos(vec_az)
dy = np.cos(vec_el)*np.sin(vec_az)
dz = np.sin(vec_el)
b = 255*(dx*uni_x + dy*uni_y + dz*uni_z)
b = b.clip(0, 255)
im = Image.fromarray(b.astype('uint8'))
im.save("b.jpg")
原圖:

結果:

四、科學計算、繪制sinx、cosx的數學規律
import numpy as np
import pylab as pl
import matplotlib.font_manager as fm
myfont = fm.FontProperties(fname=r'C:\Windows\Fonts\STKAITI.ttf')
t = np.arange(0.0, 2.0*np.pi, 0.01)
s = np.sin(t)
z = np.cos(t)
pl.plot(t, s, label='正弦')
pl.plot(t, z, label='余弦')
pl.xlabel('x-變數', fontproperties='STKAITI', fontsize=18)
pl.ylabel('y-正弦余弦函式值', fontproperties='simhei', fontsize=18)
pl.title('sin-cos函式影像', fontproperties='STLITI', fontsize=24)
pl.legend(prop=myfont)
pl.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/150273.html
標籤:Python
下一篇:Math類
