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

熱線電話:13121318867

登錄
首頁(yè)精彩閱讀8 段用于數(shù)據(jù)清洗 Python 代碼
8 段用于數(shù)據(jù)清洗 Python 代碼
2019-11-27
收藏
8 段用于<a href='/map/shujuqingxi/' style='color:#000;font-size:inherit;'>數(shù)據(jù)清洗</a> Python 代碼

作者|Kin Lim Lee

編譯|量子位

最近,大數(shù)據(jù)工程師Kin Lim Lee在Medium上發(fā)表了一篇文章,介紹了8個(gè)用于數(shù)據(jù)清洗的Python代碼。

數(shù)據(jù)清洗,是進(jìn)行數(shù)據(jù)分析和使用數(shù)據(jù)訓(xùn)練模型的必經(jīng)之路,也是最耗費(fèi)數(shù)據(jù)科學(xué)家/程序員精力的地方。

這些用于數(shù)據(jù)清洗的代碼有兩個(gè)優(yōu)點(diǎn):一是由函數(shù)編寫而成,不用改參數(shù)就可以直接使用。二是非常簡(jiǎn)單,加上注釋最長(zhǎng)的也不過11行。在介紹每一段代碼時(shí),Lee都給出了用途,也在代碼中也給出注釋。大家可以把這篇文章收藏起來,當(dāng)做工具箱使用。

涵蓋8大場(chǎng)景的數(shù)據(jù)清洗代碼

這些數(shù)據(jù)清洗代碼,一共涵蓋8個(gè)場(chǎng)景,分別是:

刪除多列、更改數(shù)據(jù)類型、將分類變量轉(zhuǎn)換為數(shù)字變量、檢查缺失數(shù)據(jù)、刪除列中的字符串、刪除列中的空格、用字符串連接兩列(帶條件)、轉(zhuǎn)換時(shí)間戳(從字符串到日期時(shí)間格式)

刪除多列

在進(jìn)行數(shù)據(jù)分析時(shí),并非所有的列都有用,用df.drop可以方便地刪除你指定的列。

def drop_multiple_col(col_names_list, df): 
 
 AIM -> Drop multiple columns based on their column names 
 INPUT -> List of column names, df
 OUTPUT -> updated df with dropped columns 
 ------
 
 df.drop(col_names_list, axis=1, inplace=True)
 return df

轉(zhuǎn)換數(shù)據(jù)類型

當(dāng)數(shù)據(jù)集變大時(shí),需要轉(zhuǎn)換數(shù)據(jù)類型來節(jié)省內(nèi)存。

def change_dtypes(col_int, col_float, df): 
 
 AIM -> Changing dtypes to save memory
 INPUT -> List of column names (int, float), df
 OUTPUT -> updated df with smaller memory 
 ------
 
 df[col_int] = df[col_int].astype( int32 )
 df[col_float] = df[col_float].astype( float32 )

將分類變量轉(zhuǎn)換為數(shù)值變量

一些機(jī)器學(xué)習(xí)模型要求變量采用數(shù)值格式。這需要先將分類變量轉(zhuǎn)換為數(shù)值變量。同時(shí),你也可以保留分類變量,以便進(jìn)行數(shù)據(jù)可視化。

def convert_cat2num(df):
 # Convert categorical variable to numerical variable
 num_encode = { col_1 : { YES :1, NO :0},
 col_2 : { WON :1, LOSE :0, DRAW :0}} 
 df.replace(num_encode, inplace=True) 

檢查缺失數(shù)據(jù)

如果你要檢查每列缺失數(shù)據(jù)的數(shù)量,使用下列代碼是最快的方法。可以讓你更好地了解哪些列缺失的數(shù)據(jù)更多,從而確定怎么進(jìn)行下一步的數(shù)據(jù)清洗和分析操作。

def check_missing_data(df):
 # check for any missing data in the df (display in descending order)
 return df.isnull().sum().sort_values(ascending=False)

刪除列中的字符串

有時(shí)候,會(huì)有新的字符或者其他奇怪的符號(hào)出現(xiàn)在字符串列中,這可以使用df[‘col_1’].replace很簡(jiǎn)單地把它們處理掉。

def remove_col_str(df):
 # remove a portion of string in a dataframe column - col_1
 df[ col_1 ].replace(, , regex=True, inplace=True)
 # remove all the characters after  (including ) for column - col_1
 df[ col_1 ].replace( .* , , regex=True, inplace=True)

刪除列中的空格

數(shù)據(jù)混亂的時(shí)候,什么情況都有可能發(fā)生。字符串開頭經(jīng)常會(huì)有一些空格。在刪除列中字符串開頭的空格時(shí),下面的代碼非常有用。

def remove_col_white_space(df):
 # remove white space at the beginning of string 
 df[col] = df[col].str.lstrip()

用字符串連接兩列(帶條件)

當(dāng)你想要有條件地用字符串將兩列連接在一起時(shí),這段代碼很有幫助。比如,你可以在第一列結(jié)尾處設(shè)定某些字母,然后用它們與第二列連接在一起。根據(jù)需要,結(jié)尾處的字母也可以在連接完成后刪除。

def concat_col_str_condition(df):
 # concat 2 columns with strings if the last 3 letters of the first column are pil
 mask = df[ col_1 ].str.endswith( pil , na=False)
 col_new = df[mask][ col_1 ] + df[mask][ col_2 ]
 col_new.replace( pil , , regex=True, inplace=True) # replace the pil with emtpy space

轉(zhuǎn)換時(shí)間戳(從字符串到日期時(shí)間格式)

在處理時(shí)間序列數(shù)據(jù)時(shí),我們很可能會(huì)遇到字符串格式的時(shí)間戳列。這意味著要將字符串格式轉(zhuǎn)換為日期時(shí)間格式(或者其他根據(jù)我們的需求指定的格式) ,以便對(duì)數(shù)據(jù)進(jìn)行有意義的分析。

def convert_str_datetime(df): 
 
 AIM -> Convert datetime(String) to datetime(format we want)
 INPUT -> df
 OUTPUT -> updated df with new datetime format 
 ------
 
 df.insert(loc=2, column= timestamp , value=pd.to_datetime(df.transdate, format= %Y-%m-%d %H:%M:%S.%f )) 

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

若不方便掃碼,搜微信號(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)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(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ù)說明請(qǐng)參見: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 = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+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); }