1. 程式人生 > >Python數據分析I

Python數據分析I

endpoint spl fig ner 存儲 markdown line wid urn

Python數據分析概述

數據分析的含義與目標

統計分析方法

提取有用信息

研究、概括、總結

Python與數據分析

Python: Guido Van Rossum Christmas Holiday, 1989

特點:簡介 開發效率搞 運算速度慢(相對於C++和Java) 膠水特性(集成C語言)

數據分析:numpy、scipy、matplotlib、pandas、scikit-learn、keras

Python數據分析大家族

numpy(Numeric Python): 數據結構基礎。是Python的一種開源的數值計算擴展。這種工具可用來存儲和處理大型矩陣,比Python自身的嵌套列表(nested list structure)結構要高效的多(該結構也可以用來表示矩陣(matrix))。據說NumPy將Python相當於變成一種免費的更強大的MatLab系統。

scipy: 強大的科學計算方法(矩陣分析、信號和圖像分析、數理分析……)

matplotlib: 豐富的可視化套件

pandas: 基礎數據分析套件。該工具是為了解決數據分析任務而創建的。Pandas 納入了大量庫和一些標準的數據模型,提供了高效地操作大型數據集所需的工具。pandas提供了大量能使我們快速便捷地處理數據的函數和方法。Pandas最初被作為金融數據分析工具而開發出來,因此,pandas為時間序列分析提供了很好的支持。 Pandas的名稱來自於面板數據(panel data)和python數據分析(data analysis)。

scikit-learn: 強大的數據分析建模庫

keras: (深度)人工神經網絡

Python環境搭建

平臺:Windows、Linux、MacOS

科學計算工具:Anaconda

Python數據分析基礎技術

I. numpy

關鍵詞: 開源 數據計算擴展

功能: ndarray 多維操作 線性代數

ndarray

#encoding=utf-8
import numpy as np
def main():
    lst=[[1,2,3],[2,4,6]]
    print(type(lst))
    np_lst=np.array(lst)
    print(type(lst))
    np_lst=np.array(lst,dtype=np.float)
    # bool
    # int,int8,int16,int32,int64,int128
    # uint8,uint16,uint32,uint64,uint128,
    # float16/32/64,complex64/128
    print(np_lst.shape)         # 行列數
    print(np_lst.ndim)          # 維數
    print(np_lst.dtype)         # 數據類型
    print(np_lst.itemsize)      # 每個數據的數據存儲大小
    print(np_lst.size)          # 元素個數

some kinds of array

#encoding=utf-8
import numpy as np
def main():
    print(np.zeros([2, 4]))
    print(np.ones([3, 5]))
    print("Rand:")
    print(np.random.rand())                 # 0-1內均勻分布隨機數
    print(np.random.rand(2, 4))
    print("RandInt:")
    print(np.random.randint(1, 10, 3))      # 3個1-10內隨機分布整數
    print("Randn:")
    print(np.random.randn(2, 4))            # 標準正態隨機數
    print("Choice:")
    print(np.random.choice([10, 20, 30]))   # 指定範圍內的隨機數
    print("Distribute:")
    print(np.random.beta(1, 10, 100))       # 比如Beta分布,Dirichlet分布etc

opeartion

#encoding=utf-8
import numpy as np
def main():
    print(np.arange(1, 11).reshape([2, 5]))
    lst = np.arange(1, 11).reshape([2, 5])
    print("Exp:")
    print(np.exp(lst))
    print("Exp2:")
    print(np.exp2(lst))
    print("Sqrt:")
    print(np.sqrt(lst))
    print("Sin:")
    print(np.sin(lst))
    print("Log:")
    print(np.log(lst))
    lst = np.array([[[1, 2, 3, 4],
                     [4, 5, 6, 7]],
                    [[7, 8, 9, 10],
                     [10, 11, 12, 13]],
                    [[14, 15, 16, 17],
                     [18, 19, 20, 21]]
                    ])
    print(lst)
    print("Sum:")
    print(lst.sum())            # 所有元素求和
    print(lst.sum(axis=0))      # 最外層求和
    print(lst.sum(axis=1))      # 第二層求和
    print(lst.sum(axis=-1))     # 最裏層求和
    print("Max:")
    print(lst.max())
    print("Min:")
    print(lst.min())

    lst1 = np.array([10, 20, 30, 40])
    lst2 = np.array([4, 3, 2, 1])
    print("Add:")
    print(lst1 + lst2)
    print("Sub:")
    print(lst1 - lst2)
    print("Mul:")
    print(lst1 * lst2)
    print("Div:")
    print(lst1 / lst2)
    print("Square:")
    print(lst1 ** lst2)
    print("Dot:")
    print(np.dot(lst1.reshape([2, 2]), lst2.reshape([2, 2])))
    print("Cancatenate")
    print(np.concatenate((lst1, lst2), axis=0))
    print(np.vstack((lst1, lst2)))                  # 按照行拼接
    print(np.hstack((lst1, lst2)))                  # 按照列拼接
    print(np.split(lst1, 2))                        # 向量拆分
    print(np.copy(lst1))                            # 向量拷貝

liner algebra

#encoding=utf-8
import numpy as np
from numpy.linalg import *
def main():
    ## Liner
    print(np.eye(3))
    lst = np.array([[1, 2],
                    [3, 4]])
    print("Inv:")
    print(inv(lst))
    print("T:")
    print(lst.transpose())
    print("Det:")
    print(det(lst))
    print("Eig:")
    print(eig(lst))
    y = np.array([[5], [7]])
    print("Solve")
    print(solve(lst, y))

others

#encoding=utf-8
import numpy as np
def main():
    ## Other
    print("FFT:")
    print(np.fft.fft(np.array([1, 1, 1, 1, 1, 1, 1, 1, 1])))
    print("Coef:")
    print(np.corrcoef([1, 0, 1], [0, 2, 1]))
    print("Poly:")
    print(np.poly1d([2, 1, 3]))             #一元多次方程

II. matplotlib

關鍵詞: 繪圖庫

Line

#encoding=utf-8
import numpy as np
import matplotlib.pyplot as plt

def Main():
    ## line
    x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
    c, s = np.cos(x), np.sin(x)
    plt.plot(x, c)
    plt.figure(1)
    plt.plot(x, c, color="blue", linewidth=1.5, linestyle="-", label="COS", alpha=0.6)
    plt.plot(x, s, "r*", label="SIN", alpha=0.6)
    plt.title("Cos & Sin", size=16)
    ax = plt.gca()                # 軸編輯器
    ax.spines["right"].set_color("none")
    ax.spines["top"].set_color("none")
    ax.spines["left"].set_position(("data", 0))
    ax.spines["bottom"].set_position(("data", 0))
    ax.xaxis.set_ticks_position("bottom")
    ax.yaxis.set_ticks_position("left")
    plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r‘$-\pi$‘, r‘$-\pi/2$‘, r‘$0$‘, r‘$\pi/2$‘, r‘$\pi$‘])                   # 正則表達
    plt.yticks(np.linspace(-1, 1, 5, endpoint=True))
    for label in ax.get_xticklabels()+ax.get_yticklabels():
        label.set_fontsize(16)
        label.set_bbox(dict(facecolor="white", edgecolor="none", alpha=0.2))
    plt.legend(loc="upper left")
    plt.grid()
    # plt.axis([-2, 1, -0.5, 1])
    # fill:填充
    plt.fill_between(x, np.abs(x) < 0.5, c, c > 0.5, color="green", alpha=0.25)
    t = 1
    plt.plot([t, t], [0, np.cos(t)], "y", linewidth=3, linestyle="--")
    plt.annotate("cos(1)", xy=(t, np.cos(1)), xycoords="data", xytext=(+10, +30),textcoords="offset points", arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
    

plt.fill_between(x, np.abs(x) < 0.5, c, c > 0.5, color="green", alpha=0.25)

第一個參數x表示x軸,第二個參數 np.abs(x)表示x的絕對值,np.abs(x) < 0.5是一個判定變量,c表示y軸,c > 0.5是一個判定條件。

當np.abs(x) < 0.5為真(1),從y軸的1(滿足c>0.5)開始往兩邊填充(當然X軸上是-0.5到0.5之間的區域),此時填充的也就是圖上方的兩小塊。當np.abs(x) >= 0.5為假(0),從y軸的0開始向上填充,當然只填充c>0.5的區域,也就是圖中那兩個大的對稱區域。

Many types of figures

#encoding=utf-8
import numpy as np
import matplotlib.pyplot as plt

def Main():
    fig = plt.figure()
    ## scatter
    ax = fig.add_subplot(3, 3, 1)
    n = 128
    X = np.random.normal(0, 1, n)
    Y = np.random.normal(0, 1, n)
    T = np.arctan2(Y, X)
    # plt.axes([0.025, 0.025, 0.95, 0.95])
    plt.scatter(X, Y, s=75, c=T, alpha=.5)
    plt.xlim(-1.5, 1.5), plt.xticks([])
    plt.ylim(-1.5, 1.5), plt.yticks([])
    plt.axis()
    plt.title("scatter")
    plt.xlabel("x")
    plt.ylabel("y")

    ## bar
    fig.add_subplot(332)
    n = 10
    X = np.arange(n)
    Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1, n)
    Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1, n)
    plt.bar(X, +Y1, facecolor=‘#9999ff‘, edgecolor=‘white‘)
    plt.bar(X, -Y2, facecolor=‘#ff9999‘, edgecolor=‘white‘)
    for x, y in zip(X,Y1):
        plt.text(x + 0.4, y + 0.05, ‘%.2f‘ % y, ha=‘center‘, va=‘bottom‘)
    for x, y in zip(X,Y2):
        plt.text(x + 0.4, - y - 0.05, ‘%.2f‘ % y, ha=‘center‘, va=‘top‘)

    ## Pie
    fig.add_subplot(333)
    n = 20
    Z = np.ones(n)
    Z[-1] *= 2
    # explode扇形離中心距離
    plt.pie(Z, explode=Z*.05, colors=[‘%f‘ % (i / float(n)) for i in range(n)],
            labels=[‘%.2f‘ % (i / float(n)) for i in range(n)])
    plt.gca().set_aspect(‘equal‘)       # 圓形
    plt.xticks([]), plt.yticks([])

    ## polar
    fig.add_subplot(334, polar=True)
    n = 20
    theta = np.arange(0, 2 * np.pi, 2 * np.pi / n)
    radii = 10 * np.random.rand(n)
    plt.polar(theta, radii)
    # plt.plot(theta, radii)

    ## heatmap
    fig.add_subplot(335)
    from matplotlib import cm
    data = np.random.rand(5, 10)
    cmap = cm.Blues
    map = plt.imshow(data, interpolation=‘nearest‘, cmap=cmap, aspect=‘auto‘, vmin=0, vmax=1)

    ## 3D
    from mpl_toolkits.mplot3d import Axes3D
    ax = fig.add_subplot(336, projection="3d")
    ax.scatter(1, 1, 3, s=100)

    ## hot map
    fig.add_subplot(313)
    def f(x, y):
        return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(- x ** 2 - y ** 2)
    n = 256
    x = np.linspace(-3, 3, n * 2)
    y = np.linspace(-3, 3, n)
    X, Y = np.meshgrid(x, y)
    plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)
    plt.savefig("./data/fig.png")
    plt.show()

Python數據分析I