python 中常用視覺化工具庫
阿新 • • 發佈:2022-05-12
python 中常用視覺化工具庫
a、Numpy常用屬性及方法
為什麼用它:它可以方便的使用陣列,矩陣進行計算,包含線性代數。傅立葉變換、隨機數生成等大量函式(處理數值型的陣列)
import numpy as np
Numpy生成array的屬性:
import numpy as np
x=np.array([1,2,3,4,5,6,7,8]) # 一維
x.shape #(8,)
X=np.array([[1,2,3,4],[5,6,7,8]]) # 二維陣列
X.shape #(2,4)
#規律:從外往裡數元素個數
操作函式
import numpy as np A=np.arange(10).reshape(2,5) # np.arrage(10)--> array([0,1,2,3,4,5,6,7,8,9]) A.shape # (2,5) A=[[0,1,2,3,4],[5,6,7,8,9]] test1=A+1 # array([[1,2,3,4,5],[6,7,8,9,10]]) test2=A+3 #array([[0,3,6,9,12],[15,18,21,24,27]]) #...... B=np.arange(1,11).reshape(2,5) test3=A+B #test3=[[1,3,5,7,9],[11,13,15,17,19]] test4=B-A #test4=[[1,1,1,1,1],[1,1,1,1,1]]
索引查詢
# array[:10] 取前10個數
# array[-3:] 去最後3個數
#
import numpy as np
C=np.random.randint(1,100,10)
#C[-3:]=10#[77 1 30 3 31 10 92 10 10 10]
# 獲取陣列中最大的前N個數字、
#argsort() 傳回排序後的索引下標
print(C[C.argsort()])#排序[ 5 11 31 39 53 53 85 88 95 99]
print(C[C.argsort()[-3:]])#取最大的3個元素[88 95 99]
Numpy中的數學統計函式
import numpy as np t = np.array([1, 2, 3, 4, 5]) t1=t.sum()#15求和 t2 = t.mean()#3.0 平均值 t3=t.min()#1 最小值 t4=np.median(t) #3.0 中位數 t5 = t.var() # 2.0 方差 t6=t.std()#1.4142135623730951 標準差
Numpy的向量化操作
t = np.array([1, 2, 3, 4, 5])
n=t[t>3].size #注意!沒有括號 當然len(t[t>3])也能實現,但是t[t>3].size效能更好,所有時間更短
print(n)
Numpy數組合並
t1=np.array([1,2,3,4]) #t2=np.array([5,6,7,8]) t2=np.array([[5,6,7,8], [9,10,11,12]]) t3=np.vstack([t1,t2]) #[[1 2 3 4],[5 6 7 8]] #t4=np.hstack([t1,t2]) #[1,2,3,4,5,6,7,8] #注意: #1.vstack:使用是必須保持每個一維數組裡的元素裡的個數相同 #即:t1=np.array([1,2,3,4]) # t2=np.array([[5,6,7,8], # [9,10,11,12]]) # 這種情況下使用vstack會報錯 #ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 3 and the array at index 1 has size 4 #2.同理:hstack使用是必須保持每個二維數組裡的一維陣列個數相同 #即:t1=np.array([1,2,3,4]) # t2=np.array([[5,6,7,8], # [9,10,11,12]]) # 此時np.hstack([t1,t2]) 會報錯 #ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)
案例二:
t1=np.array([[1,2,3,4],
[5,6,7,8]])
t2=np.array([[5,6,7,8],
[1,2,3,4]])
t3=np.vstack([t1,t2])
t4=np.hstack([t1,t2])
print(t3)
#[[1 2 3 4]
#[5 6 7 8]
#[5 6 7 8]
#[1 2 3 4]]
print(t4)
#[[1 2 3 4 5 6 7 8]
# [5 6 7 8 1 2 3 4]]
b、pandas
為什麼用pandas:它能幫我們處理數值(基於numpy)和字串及時間序列
pandas的常用方法
Series與DataFrame
data1=[{"name":"黃勇","age":20,"sex":"男"},{"name":"小勇子","age":21,"sex":"男"}]
data2={"name":["hy","xyz"],"age":[20,19],"sex":["男","男"]}
r1=pd.Series(data1)
"""0 {'name': '黃勇', 'age': 20, 'sex': '男'}
1 {'name': '小勇子', 'age': 21, 'sex': '男'}
dtype: object
"""
df1=pd.DataFrame(data1)
'''
name age sex
0 黃勇 20 男
1 小勇子 21 男
'''
r3 = pd.Series(data2)
'''
name [hy, xyz]
age [20, 19]
sex [男, 男]
dtype: object
'''
df2 = pd.DataFrame(data2)
'''
name age sex
0 hy 20 男
1 xyz 19 男
'''
r5=np.vstack([df1,df2])
'''
[['黃勇' 20 '男']
['小勇子' 21 '男']
['hy' 20 '男']
['xyz' 19 '男']]
'''
#print(df1["name"].values.reshape(-1, 1).shape) #(2,1) [[""],[""]]
r6=np.hstack([df1["name"].values.reshape(-1,1),df2["age"].values.reshape(-1,1)])
'''
[['黃勇' 20]
['小勇子' 19]]
'''
#選擇多少行多少列
'''
data.csv
是否客棧,評論數,房間數,酒店總間夜
0,686,127,223
0,354,128,64
1,58,50,3
0,65,168,43
0,303,97,69
0,31,314,229'''
data= pd.read_csv("data/data_hotel_mult.csv")
x=data.iloc[:,:-1]#取所有行到最後一列,不包含最後一列
'''
是否客棧 評論數 房間數
0 0 686 127
1 0 354 128
2 1 58 50
3 0 65 168
4 0 303 97
5 0 31 314
'''
c、sklearn
邏輯迴歸
d、matplotlib
為什麼用它:它能將資料進行視覺化,將資料更 直觀的呈現,使資料更加客觀,更具說服力
使用:
# 導包
from matplotlib import pyplot as plt
繪圖型別:
函式名稱 | 描述 |
---|---|
Bar | 繪製條形圖(柱狀圖) |
Plot | 在座標軸上畫線或者標記 |
Scatter | 繪製x與y的散點圖 |
hist | 繪製直方圖 |
畫圖步驟:
#修改matplotlib預設的字型(需要顯示中文就設定)
matplotlib.rc("font",family="KaiTi",weight="bold",size="18")
a = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
b= [0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,1,1,1]
plt.figure(figsize=(20,8))
x=[i for i in range(11,31)]
#設定圖名稱
plt.title("我與同桌女朋友個數對比")
#設定軸名稱
plt.xlabel("年齡")
plt.ylabel("女朋友個數")
#設定網格alpha為不透明度
plt.grid(alpha=0.3)
#label設定這條折線的圖例名稱
plt.plot(x,b,label="自己",lineStyle="dashed") #折線圖
plt.plot(x,a,label="同桌")
#圖例(顯示圖例,必須放在plot下)
plt.legend(loc="upper left")
# 設定x軸刻度
_xtick_labels = [f"{i}歲" for i in x]
plt.xticks(x,_xtick_labels)
plt.show()
各圖中屬性配置
plot()函式是繪製二維圖形的最基本函式。用於畫圖它可以繪製點和線,語法格式如下:
# 常用語法
plot(x, y,ls='--',c='r',lw='12.5')
#解釋:ls=lineStyle,c=color,lw=lineWidth
#有幾條線,就呼叫幾次plot()
marker 可以定義的符號如下:
標記 | 符號 | 描述 |
---|---|---|
"." | 點 | |
"None", " " or "" | 沒有任何標記 | |
"*" | 星號 |
線型別:
線型別標記 | 描述 |
---|---|
'-' | 實線 |
':' | 點虛線 |
'--' | 破折線(dashed) |
'-.' | 點劃線 |
顏色型別:
顏色標記 | 描述 |
---|---|
'r' | 紅色 |
'g' | 綠色 |
'b' | 藍色 |
'c' | 青色 |
'm' | 品紅 |
'y' | 黃色 |
'k' | 黑色 |
'w' | 白色 |
柱狀圖:
#水平柱狀圖:
plt.bar(x,y,width=0.8,color='r')
#垂直柱狀圖:
plt.barh(x,y)
散點圖:
color='r' #所有點同一個顏色
color=['r','b'...] #定義每一個點的顏色
plt.scatter(x,y,c=color,s=30.4)
解釋:s=size
直方圖:
a=[131,98,125, 131, 124, 138, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119,128,121]
#組距
d=4
m=max(a)
n=min(a)
#畫布
plt.figure(figsize=(20,8),dpi=80)
plt.hist(a)
plt.grid(alpha=0.3)
#設定刻度
plt.xticks(range(n,m+d,d))
plt.show()