機器學習三劍客:numpy、pandas、matplotlib
NumPy系統是Python的一種開源的數值計算擴展。這種工具可用來存儲和處理大型矩陣。
pandas 是基於numpy的一種工具,該工具是為了解決數據分析任務而創建的。
Matplotlib 是一個 Python 的 2D繪圖庫,它以各種硬拷貝格式和跨平台的交互式環境生成出版質量級別的圖形。
柱狀圖bar
from matplotlib import pyplot as plt import matplotlib # 顯示圖表,僅限於jupyter使用 %matplotlib inline #指定默認字體 matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 第一個參數:索引 # 第二個參數:高度 參數必須對應否則報錯 plt.bar(range(5),[100,200,300,400,500],color='red') plt.xticks(range(5),['A','B','C','D','E']) plt.xlabel('姓名') plt.ylabel('得分') plt.title('學生得分')
# 或顯示圖標Plt.show()
餅圖pie
labels = ['A','B','C','D'] # autopct='%1.1f%%'顯示比列,格式化顯示一位小數,固定寫法 plt.pie([50,39,50,20],labels=labels,autopct='%1.1f%%') plt.title('人口比例')
直方圖hist
from matplotlib import pyplot as plt import matplotlib heights = [180,160,172,177,160] plt.hist(heights,color='red',alpha=0.5) # 橫軸heights,縱軸當前值的個數 plt.xlabel('身高') plt.ylabel('人數') plt.title('身高統計')
散點圖scatter
# 5、繪制一個散點圖 # 用random模塊獲取兩組數據,分別代表橫縱坐標。一組數據里有50個數, # 用隨機種子的方法固定住random模塊獲取得到的數據 # 並將散點圖里的符號變為'*' import numpy as np np.random.seed(10) # 隨機種子,將隨機數固定住 heights = [] weights = [] heights.append(np.random.randint(150,185,size=50)) # weights.append(np.random.normal(loc=50,scale=100,size)) # 生成正太分布,也稱高斯分布 weights.append(np.random.randint(50,100,size=50)) plt.scatter(heights,weights,marker='*',color='yellow') #默認是圓點,marker='*'
折線圖plot
x = [4,65,71,5,3] y = [3,12,5,2,3] plt.plot(x,y) # plt.savefig('a.jpg') # 保存圖片
面積圖
from matplotlib import pyplot as plt import numpy as np # 導入3D模塊 from mpl_toolkits.mplot3d.axes3d import Axes3D import matplotlib #指定默認字體 matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 面積圖 def test_area(): date = ['2000-01-01','2000-02-01','2000-03-01','2000-04-01'] earn = [156,356,156,30] eat = [10,20,30,40] drink = [20,20,30,40] play = [20,20,30,40] # [20,20,30,40]] plt.stackplot(date,earn,eat,drink,play,colors=['red','yellow','green','blue']) plt.title('收入支出面積圖展示') plt.plot([],[],color='red',label='收入') plt.plot([],[],color='yellow',label='吃') plt.plot([],[],color='green',label='喝') plt.plot([],[],color='blue',label='玩') # 展示圖例 plt.legend() plt.show() test_area()
3D餅圖突出展示
def test_pie(): beijing = [10,20,30,40] label = ['2-3年','3-4年','4-5年','5年'] color = ['red','yellow','green','blue'] indict = [] for index,item in enumerate(beijing): # 判斷優先級 if item == max(beijing): indict.append(0.3) elif index == 1: indict.append(0.2) else: indict.append(0) plt.pie(beijing,labels=label,colors=color,startangle=90,shadow=True,explode=tuple(indict),autopct='%1.1f%%') plt.title('3D切割凸顯餅圖') plt.show() test_pie()
條形圖
def test_barh(): price = [11,22,33,44] plt.barh(range(4),price,align='center',color='red',alpha=0.5) plt.xlabel('價格') plt.yticks(range(4),['紅樓夢','西游記','水滸傳','三國演義']) plt.title('四大名著') plt.show() test_barh()
3D散點圖
def test_scatter_3D(): x = np.random.randint(0,10,size=100) y = np.random.randint(0,10,size=100) z = np.random.randint(0,10,size=100) # 創建二維對象 fig = plt.figure() # 強轉 axes3d = Axes3D(fig) # 填充數據 axes3d.scatter(x,y,z) plt.show() test_scatter_3D()
趨勢圖
def test_line(): x = ['2000-01-03','2000-02-03','2000-03-03','2000-04-03'] # 定義y軸數據 y1 = [0,3,5,7] y2 = [11,22,33,44] plt.plot(x,y1,label='tempreature') plt.plot(x,y2,label='water') # 顯示圖例 plt.legend() plt.show() test_line()
箱型圖
import pandas as pd # 定義消費分析 def test_tips(pd): # 讀取數據集 df = pd.read_excel('tips.xlsx','sheet1') # 繪制散點圖證明推論:小費隨着總賬單的遞增而遞增 # df.plot(kind='scatter',x='tip',y='total_bill',c='red',label='bill_tip') # 繪制箱型圖 # 計算小費占總賬單的比例 df['pct'] = df.tip / df.total_bill * 100 # print(df) # 過濾出小費占比比較高的人群,例如:30%以上 print(df[df.pct > 30]) # 刪除異常數據,按照索引刪除 df = df.drop([67,172,178]) # print(df) # 打印箱型圖 df.pct.plot(kind='box',label='tips pct%') # 繪制 plt.show() test_tips(pd)
散點圖繪制如下:
箱型圖繪制如下:
對比柱狀圖、小提琴圖
import seaborn as sns # 定義數據分析方法 def test_excel(): # 讀取數據集 df = pd.read_excel('test.xlsx','sheet1') # print(df) # 需求 # 計算按性別和人體質量分組,求銷售額 # select sum(sales),gender,BMI from test group by gender,BMI myexcel = df.groupby(['BMI','Gender']).Sales.sum() print(myexcel) # 繪制對比柱狀圖unstack myexcel.unstack().plot(kind='bar',stacked=True,color=['red','green']) # # 利用seaborn繪制,小提琴圖 # sns.violinplot(df['Age'],df['Gender']) # # 初始化數據 # sns.despine() # 繪制 plt.show() test_excel()
柱狀圖效果如下:
小提琴效果圖如下: