學習Python大資料處理模組Pandas,pythonpandas

來源:互聯網
上載者:User

學習Python大資料處理模組Pandas,pythonpandas

適合初學入門

第一課 構造資料

本節基本瞭解Pandas裡的一些資料結構和模組的基本使用,初步瞭解Pandas的提供的一些功能,學會基本使用。

建立資料

通過Python的zip構造出一元組組成的列表作為DataFrame的輸入資料rec。

In [3]: import pandas as pdIn [4]: import randomIn [5]: num = random.sample(xrange(10000, 1000000), 5)In [6]: numOut[6]: [244937, 132008, 278446, 613409, 799201]In [8]: names = "hello the cruel world en".split()In [9]: namesOut[9]: ['hello', 'the', 'cruel', 'world', 'en']In [10]: rec = zip(names, num)In [15]: data = pd.DataFrame(rec, columns = [u"姓名",u"業績" ])In [16]: dataOut[16]:     姓名  業績0    hello   2449371    the     1320082    cruel   2784463    world   6134094    en      799201 

DataFrame方法函數的第一個參數是資料來源,第二個參數columns是輸出資料表的表頭,或者說是表格的欄位名。


匯出資料csv

Windows平台上的編碼問題,我們可以先做個簡單處理,是ipython-notebook支援utf8.

import sysreload(sys)sys.setdefaultencoding("utf8")

接下來可以資料匯出了。

In [31]: dataOut[31]:     姓名  業績0    hello   2449371    the     1320082    cruel   2784463    world   6134094    en      799201 #在ipython-note裡後加問號可查協助,q退出協助In [32]: data.to_csv?In [33]: data.to_csv("c:\\out.csv", index = True, header = [u"僱員", u"銷售業績"])

將data匯出到out.csv檔案裡,index參數是指是否有主索引,header如果不指定則是以data裡columns為頭,如果指定則是以後邊列表裡的字串為表頭,但要注意的是header後的字串列表的個數要和data裡的columns欄位個數相同。



可到c盤用Notepad++開啟out.csv看看。

簡單的資料分析
In [43]: dataOut[43]:     姓名  業績0    hello   2449371    the     1320082    cruel   2784463    world   6134094    en      799201#排序並取前三名In [46]: Sorted = data.sort([u"業績"], ascending=False)         Sorted.head(3)Out[46]:     姓名  業績4    en      7992013    world   6134092    cruel   278446


圖形輸出
In [71]: import matplotlib.pyplot as plt         #使ipython-notebook支援matplotlib繪圖         %matplotlib inlineIn [74]: df = data         #繪圖         df[u"業績"].plot()         MaxValue = df[u"業績"].max()         MaxName = df[u"姓名"][df[u"業績"] == df[u"業績"].max()].values         Text = str(MaxValue) + " - " + MaxName         #給圖添加文本標註         plt.annotate(Text, xy=(1, MaxValue), xytext=(8, 0), xycoords=('axes fraction', 'data'), textcoords='offset points')


如果注釋掉plt.annotate這行,結果如下所示:









聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.