溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python使用Pandas處理數(shù)據(jù)的方法

發(fā)布時(shí)間:2020-06-17 13:50:10 來(lái)源:億速云 閱讀:257 作者:鴿子 欄目:編程語(yǔ)言

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)大之處。

1.創(chuàng)建數(shù)據(jù)

使用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),
    }
)
  • a1和a2:從正態(tài)(高斯)分布中抽取的隨機(jī)樣本。
  • a3:0到4中的隨機(jī)整數(shù)。
  • y1:從0到1的對(duì)數(shù)刻度均勻分布。
  • y2:0到1中的隨機(jī)整數(shù)。

生成如下所示的數(shù)據(jù):

python使用Pandas處理數(shù)據(jù)的方法

2.繪制圖像

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()

python使用Pandas處理數(shù)據(jù)的方法

我們還可以自定義一張圖上顯示多少個(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()

python使用Pandas處理數(shù)據(jù)的方法

3.繪制直方圖

Pandas能夠讓我們用非常簡(jiǎn)單的方式獲得兩個(gè)圖形的形狀對(duì)比:

df[["a1", "a2"]].plot(bins=30, kind="hist")
plt.show()

python使用Pandas處理數(shù)據(jù)的方法

還能允許多圖繪制:

df[["a1", "a2"]].plot(bins=30, kind="hist", subplots=True)
plt.show()

python使用Pandas處理數(shù)據(jù)的方法

當(dāng)然,生成折線圖也不在畫(huà)下:

df[['a1', 'a2']].plot(by=df.y2, subplots=True)
plt.show()

python使用Pandas處理數(shù)據(jù)的方法

4.線性擬合

Pandas還能用于擬合,讓我們用pandas找出一條與下圖最接近的直線:

python使用Pandas處理數(shù)據(jù)的方法

最小二乘法計(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使用Pandas處理數(shù)據(jù)的方法

以上就是值得一看的Python高效數(shù)據(jù)處理的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注億速云其它相關(guān)文章!

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

AI