Python 數(shù)據(jù)分析之逐塊讀取文本的實(shí)現(xiàn)
《利用Python進(jìn)行數(shù)據(jù)分析》,第 6 章的數(shù)據(jù)加載操作 read_xxx,有 chunksize 參數(shù)可以進(jìn)行逐塊加載。
經(jīng)測(cè)試,它的本質(zhì)就是將文本分成若干塊,每次處理 chunksize 行的數(shù)據(jù),最終返回一個(gè)TextParser 對(duì)象,對(duì)該對(duì)象進(jìn)行迭代遍歷,可以完成逐塊統(tǒng)計(jì)的合并處理。
示例代碼文中的示例代碼分析如下:
from pandas import DataFrame,Seriesimport pandas as pd path=’D:/AStudy2018/pydata-book-2nd-edition/examples/ex6.csv’# chunksize return TextParserchunker=pd.read_csv(path,chunksize=1000) # an array of Seriestot=Series([])chunkercount=0for piece in chunker:print ’------------piece[key] value_counts start-----------’#piece is a DataFrame,lenth is chunksize=1000,and piece[key] is a Series ,key is int ,value is the key columnprint piece[’key’].value_counts()print ’------------piece[key] value_counts end-------------’#piece[key] value_counts is a Series ,key is the key column, and value is the key counttot=tot.add(piece[’key’].value_counts(),fill_value=0)chunkercount+=1 #last order the seriestot=tot.order(ascending=False)print chunkercountprint ’--------------’流程分析
首先,例子數(shù)據(jù) ex6.csv 文件總共有 10000 行數(shù)據(jù),使用 chunksize=1000 后,read_csv操作返回一個(gè) TextParser 對(duì)象,該對(duì)象總共有10個(gè)元素,遍歷過(guò)程中打印 chunkercount驗(yàn)證得到。
其次,每個(gè) piece 對(duì)象是一個(gè) DataFrame 對(duì)象,piece[’key’] 得到的是一個(gè) Series 對(duì)象,默認(rèn)是數(shù)值索引,值為 csv 文件中的 key 列的值,即各個(gè)字符串。
將每個(gè) Series 的 value_counts 作為一個(gè)Series,與上一次統(tǒng)計(jì)的 tot 結(jié)果進(jìn)行 add 操作,最終得到所有塊數(shù)據(jù)中各個(gè) key 的累加值。
最后,對(duì) tot 進(jìn)行 order 排序,按降序得到各個(gè) key 的值在 csv 文件中出現(xiàn)的總次數(shù)。
這里很巧妙了使用 Series 對(duì)象的 add 操作,對(duì)兩個(gè) Series 執(zhí)行 add 操作,即合并相同key:key相同的記錄的值累加,key不存在的記錄設(shè)置填充值為0。
輸出結(jié)果為:
到此這篇關(guān)于Python 數(shù)據(jù)分析之逐塊讀取文本的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python 逐塊讀取文本內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法2. Nginx+php配置文件及原理解析3. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題4. .NET中l(wèi)ambda表達(dá)式合并問(wèn)題及解決方法5. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析6. 淺談python出錯(cuò)時(shí)traceback的解讀7. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解8. Ajax實(shí)現(xiàn)表格中信息不刷新頁(yè)面進(jìn)行更新數(shù)據(jù)9. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼10. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向
