您好,登錄后才能下訂單哦!
Pandas是Python中非常常用的數(shù)據(jù)處理工具,使用起來(lái)非常方便。它建立在NumPy數(shù)組結(jié)構(gòu)之上,所以它的很多操作通過(guò)NumPy或者Pandas自帶的擴(kuò)展模塊編寫(xiě),這些模塊用Cython編寫(xiě)并編譯到C,并且在C上執(zhí)行,因此也保證了處理速度。
今天我們就來(lái)體驗(yàn)一下它的強(qiáng)大之處。
使用pandas可以很方便地進(jìn)行數(shù)據(jù)創(chuàng)建,現(xiàn)在讓我們創(chuàng)建一個(gè)5列1000行的pandas DataFrame:
mu1, sigma1 = 0, 0.1 mu2, sigma2 = 0.2, 0.2 n = 1000df = pd.DataFrame( { "a1": pd.np.random.normal(mu1, sigma1, n), "a2": pd.np.random.normal(mu2, sigma2, n), "a3": pd.np.random.randint(0, 5, n), "y1": pd.np.logspace(0, 1, num=n), "y2": pd.np.random.randint(0, 2, n), } )
生成如下所示的數(shù)據(jù):
Pandas 繪圖函數(shù)返回一個(gè)matplotlib的坐標(biāo)軸(Axes),所以我們可以在上面自定義繪制我們所需要的內(nèi)容。比如說(shuō)畫(huà)一條垂線和平行線。這將非常有利于我們:
1.繪制平均線
2.標(biāo)記重點(diǎn)的點(diǎn)
import matplotlib.pyplot as plt ax = df.y1.plot() ax.axhline(6, color="red", linestyle="--") ax.axvline(775, color="red", linestyle="--") plt.show()
我們還可以自定義一張圖上顯示多少個(gè)表:
fig, ax = plt.subplots(2, 2, figsize=(14,7)) df.plot(x="index", y="y1", ax=ax[0, 0]) df.plot.scatter(x="index", y="y2", ax=ax[0, 1]) df.plot.scatter(x="index", y="a3", ax=ax[1, 0]) df.plot(x="index", y="a1", ax=ax[1, 1]) plt.show()
Pandas能夠讓我們用非常簡(jiǎn)單的方式獲得兩個(gè)圖形的形狀對(duì)比:
df[["a1", "a2"]].plot(bins=30, kind="hist") plt.show()
還能允許多圖繪制:
df[["a1", "a2"]].plot(bins=30, kind="hist", subplots=True) plt.show()
當(dāng)然,生成折線圖也不在畫(huà)下:
df[['a1', 'a2']].plot(by=df.y2, subplots=True) plt.show()
Pandas還能用于擬合,讓我們用pandas找出一條與下圖最接近的直線:
最小二乘法計(jì)算和該直線最短距離:
df['ones'] = pd.np.ones(len(df)) m, c = pd.np.linalg.lstsq(df[['index', 'ones']], df['y1'], rcond=None)[0]
根據(jù)最小二乘的結(jié)果繪制y和擬合出來(lái)的直線:
df['y'] = df['index'].apply(lambda x: x * m + c) df[['y', 'y1']].plot() plt.show()
以上就是值得一看的Python高效數(shù)據(jù)處理的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注億速云其它相關(guān)文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。