99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀入門必學(xué)!在Python中利用Pandas庫處理大數(shù)據(jù)
入門必學(xué)!在Python中利用Pandas庫處理大數(shù)據(jù)
2015-12-09
收藏

來源 腳本之家


在數(shù)據(jù)分析領(lǐng)域,最熱門的莫過于Python和R語言,此前有一篇文章《別老扯什么Hadoop了,你的數(shù)據(jù)根本不夠大》指出:只有在超過5TB數(shù)據(jù)量的規(guī)模下,Hadoop才是一個(gè)合理的技術(shù)選擇。這次拿到近億條日志數(shù)據(jù),千萬級(jí)數(shù)據(jù)已經(jīng)是關(guān)系型數(shù)據(jù)庫的查詢分析瓶頸,之前使用過Hadoop對大量文本進(jìn)行分類,這次決定采用Python來處理數(shù)據(jù):
硬件環(huán)境
CPU:3.5 GHz Intel Core i7
內(nèi)存:32 GB HDDR 3 1600 MHz
硬盤:3 TB Fusion Drive
數(shù)據(jù)分析工具
Python:2.7.6
Pandas:0.15.0
IPython notebook:2.0.0
源數(shù)據(jù)如下表所示:

數(shù)據(jù)讀取
啟動(dòng)IPython notebook,加載pylab環(huán)境:
ipython notebook --pylab=inline
Pandas提供了IO工具可以將大文件分塊讀取,測試了一下性能,完整加載9800萬條數(shù)據(jù)也只需要263秒左右,還是相當(dāng)不錯(cuò)了。
import pandas as pd
reader = pd.read_csv('data/servicelogs', iterator=True)
try:
df = reader.get_chunk(100000000)
except StopIteration:
print "Iteration is stopped."

使用不同分塊大小來讀取再調(diào)用 pandas.concat 連接DataFrame,chunkSize設(shè)置在1000萬條左右速度優(yōu)化比較明顯
loop = True
chunkSize = 100000
chunks = []
while loop:
try:
  chunk = reader.get_chunk(chunkSize)
  chunks.append(chunk)
except StopIteration:
  loop = False
   print "Iteration is stopped."
df = pd.concat(chunks, ignore_index=True)
下面是統(tǒng)計(jì)數(shù)據(jù),Read Time是數(shù)據(jù)讀取時(shí)間,Total Time是讀取和Pandas進(jìn)行concat操作的時(shí)間,根據(jù)數(shù)據(jù)總量來看,對5~50個(gè)DataFrame對象進(jìn)行合并,性能表現(xiàn)比較好。


如果使用Spark提供的Python Shell,同樣編寫Pandas加載數(shù)據(jù),時(shí)間會(huì)短25秒左右,看來Spark對Python的內(nèi)存使用都有優(yōu)化。
數(shù)據(jù)清洗
Pandas提供了 DataFrame.describe 方法查看數(shù)據(jù)摘要,包括數(shù)據(jù)查看(默認(rèn)共輸出首尾60行數(shù)據(jù))和行列統(tǒng)計(jì)。由于源數(shù)據(jù)通常包含一些空值甚至空列,會(huì)影響數(shù)據(jù)分析的時(shí)間和效率,在預(yù)覽了數(shù)據(jù)摘要后,需要對這些無效數(shù)據(jù)進(jìn)行處理。
首先調(diào)用 DataFrame.isnull() 方法查看數(shù)據(jù)表中哪些為空值,與它相反的方法是 DataFrame.notnull() ,Pandas會(huì)將表中所有數(shù)據(jù)進(jìn)行null計(jì)算,以True/False作為結(jié)果進(jìn)行填充,如下圖所示:

Pandas的非空計(jì)算速度很快,9800萬數(shù)據(jù)也只需要28.7秒。得到初步信息之后,可以對表中空列進(jìn)行移除操作。嘗試了按列名依次計(jì)算獲取非 空列,和 DataFrame.dropna() 兩種方式,時(shí)間分別為367.0秒和345.3秒,但檢查時(shí)發(fā)現(xiàn) dropna() 之后所有的行都沒有了,查了Pandas手冊,原來不加參數(shù)的情況下, dropna() 會(huì)移除所有包含空值的行。如果只想移除全部為空值的列,需要加上 axis 和 how 兩個(gè)參數(shù):
df.dropna(axis=1, how='all')
共移除了14列中的6列,時(shí)間也只消耗了85.9秒。
接下來是處理剩余行中的空值,經(jīng)過測試,在 DataFrame.replace() 中使用空字符串,要比默認(rèn)的空值NaN節(jié)省一些空間;但對整個(gè)CSV文件來說,空列只是多存了一個(gè)“,”,所以移除的9800萬 x 6列也只省下了200M的空間。進(jìn)一步的數(shù)據(jù)清洗還是在移除無用數(shù)據(jù)和合并上。
對數(shù)據(jù)列的丟棄,除無效值和需求規(guī)定之外,一些表自身的冗余列也需要在這個(gè)環(huán)節(jié)清理,比如說表中的流水號(hào)是某兩個(gè)字段拼接、類型描述等,通過對這些數(shù)據(jù)的丟棄,新的數(shù)據(jù)文件大小為4.73GB,足足減少了4.04G!
數(shù)據(jù)處理
使用 DataFrame.dtypes 可以查看每列的數(shù)據(jù)類型,Pandas默認(rèn)可以讀出int和float64,其它的都處理為object,需要轉(zhuǎn)換格式的一般為日期時(shí)間。 DataFrame.astype() 方法可對整個(gè)DataFrame或某一列進(jìn)行數(shù)據(jù)格式轉(zhuǎn)換,支持Python和NumPy的數(shù)據(jù)類型。
df['Name'] = df['Name'].astype(np.datetime64
對數(shù)據(jù)聚合,我測試了 DataFrame.groupby 和 DataFrame.pivot_table 以及 pandas.merge ,groupby 9800萬行 x 3列的時(shí)間為99秒,連接表為26秒,生成透視表的速度更快,僅需5秒。
df.groupby(['NO','TIME','SVID']).count() # 分組
fullData = pd.merge(df, trancodeData)[['NO','SVID','TIME','CLASS','TYPE']] # 連接
actions = fullData.pivot_table('SVID', columns='TYPE', aggfunc='count') # 透視表
根據(jù)透視表生成的交易/查詢比例餅圖:

將日志時(shí)間加入透視表并輸出每天的交易/查詢比例圖:
total_actions = fullData.pivot_table('SVID', index='TIME', columns='TYPE', aggfunc='count')
total_actions.plot(subplots=False, figsize=(18,6), kind='area')

除此之外,Pandas提供的DataFrame查詢統(tǒng)計(jì)功能速度表現(xiàn)也非常優(yōu)秀,7秒以內(nèi)就可以查詢生成所有類型為交易的數(shù)據(jù)子表:
tranData = fullData[fullData['Type'] == 'Transaction']
該子表的大小為 [10250666 rows x 5 columns]。在此已經(jīng)完成了數(shù)據(jù)處理的一些基本場景。實(shí)驗(yàn)結(jié)果足以說明,在非“>5TB”數(shù)據(jù)的情況下,Python的表現(xiàn)已經(jīng)能讓擅長使用統(tǒng)計(jì)分析語言的數(shù)據(jù)分析師游刃有余。


 

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }