值得一看的Python高效數(shù)據(jù)處理
Pandas是Python中非常常用的數(shù)據(jù)處理工具,使用起來非常方便。它建立在NumPy數(shù)組結(jié)構(gòu)之上,所以它的很多操作通過NumPy或者Pandas自帶的擴展模塊編寫,這些模塊用Cython編寫并編譯到C,并且在C上執(zhí)行,因此也保證了處理速度。
今天我們就來體驗一下它的強大之處。
1.創(chuàng)建數(shù)據(jù)
使用pandas可以很方便地進行數(shù)據(jù)創(chuàng)建,現(xiàn)在讓我們創(chuàng)建一個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), } )
- a1和a2:從正態(tài)(高斯)分布中抽取的隨機樣本。
- a3:0到4中的隨機整數(shù)。
- y1:從0到1的對數(shù)刻度均勻分布。
- y2:0到1中的隨機整數(shù)。
生成如下所示的數(shù)據(jù):
2.繪制圖像
Pandas 繪圖函數(shù)返回一個matplotlib的坐標軸(Axes),所以我們可以在上面自定義繪制我們所需要的內(nèi)容。比如說畫一條垂線和平行線。這將非常有利于我們:
1.繪制平均線
2.標記重點的點
import matplotlib.pyplot as plt ax = df.y1.plot() ax.axhline(6, color="red", linestyle="--") ax.axvline(775, color="red", linestyle="--") plt.show()
我們還可以自定義一張圖上顯示多少個表:
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()
3.繪制直方圖
Pandas能夠讓我們用非常簡單的方式獲得兩個圖形的形狀對比:
df[["a1", "a2"]].plot(bins=30, kind="hist") plt.show()
還能允許多圖繪制:
df[["a1", "a2"]].plot(bins=30, kind="hist", subplots=True) plt.show()
當然,生成折線圖也不在畫下:
df[['a1', 'a2']].plot(by=df.y2, subplots=True) plt.show()
4.線性擬合
Pandas還能用于擬合,讓我們用pandas找出一條與下圖最接近的直線:
最小二乘法計算和該直線最短距離:
df['ones'] = pd.np.ones(len(df)) m, c = pd.np.linalg.lstsq(df[['index', 'ones']], df['y1'], rcond=None)[0]
根據(jù)最小二乘的結(jié)果繪制y和擬合出來的直線:
df['y'] = df['index'].apply(lambda x: x * m + c) df[['y', 'y1']].plot() plt.show()
感謝大家的閱讀,希望大家收益多多。
本文轉(zhuǎn)自:https://blog.csdn.net/u010751000/article/details/106735872
推薦教程:《python教程》