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. 理解PHP5中static和const關(guān)鍵字2. Android table布局開(kāi)發(fā)實(shí)現(xiàn)簡(jiǎn)單計(jì)算器3. python 代碼實(shí)現(xiàn)k-means聚類分析的思路(不使用現(xiàn)成聚類庫(kù))4. IntelliJ IDEA安裝插件的方法步驟5. Java如何基于反射機(jī)制獲取不同的類6. php模擬實(shí)現(xiàn)斗地主發(fā)牌7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Android 在 res/layout 文件夾 下創(chuàng)建一個(gè) 子文件夾實(shí)例9. PHP安全-命令注入10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備