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è)元素,遍歷過程中打印 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. ASP實(shí)現(xiàn)加法驗(yàn)證碼2. 使用FormData進(jìn)行Ajax請(qǐng)求上傳文件的實(shí)例代碼3. XML入門的常見問題(二)4. layui Ajax請(qǐng)求給下拉框賦值的實(shí)例5. Jsp中request的3個(gè)基礎(chǔ)實(shí)踐6. ASP.NET MVC使用異步Action的方法7. chat.asp聊天程序的編寫方法8. CSS hack用法案例詳解9. 詳解瀏覽器的緩存機(jī)制10. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?
