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

熱線電話:13121318867

登錄
首頁大數(shù)據(jù)時代數(shù)據(jù)清洗之python實現(xiàn)缺失值處理
數(shù)據(jù)清洗之python實現(xiàn)缺失值處理
2020-07-24
收藏

在實際的數(shù)據(jù)清洗過程中,我們經(jīng)常會遇到數(shù)據(jù)內(nèi)容丟失的情況,這些丟失的數(shù)據(jù)內(nèi)容就是缺失值。缺失值的產(chǎn)生的原因多種多樣,主要分為機(jī)械原因和人為原因。

機(jī)械原因,也就是由于例如,數(shù)據(jù)存儲失敗,存儲器損壞,機(jī)械故障等原因,某段時間數(shù)據(jù)未能收集,或保存的失敗,從而造成的數(shù)據(jù)缺失。人為原因,主要是由于人的主觀失誤、歷史局限或有意隱瞞造成的數(shù)據(jù)缺失。比如,在市場調(diào)查中被訪人拒絕透露相關(guān)問題的答案,或者回答的問題是無效的,數(shù)據(jù)錄入人員失誤漏錄了數(shù)據(jù)。不管是哪種原因造成的,我們都必須對缺失數(shù)據(jù)進(jìn)行妥善處理,才能更好的保證最終數(shù)據(jù)分析結(jié)果的正確性和準(zhǔn)確性。下面小編就介紹幾種缺失值處理常用的方法,希望對大家有所幫助。

1.刪除

如果缺失值的個數(shù)只占整體很小一部分的情況下,可以刪除缺失值。

這種方法是將存在缺失值的數(shù)據(jù)條目(包括:對象,元組,記錄)進(jìn)行刪除。簡單便捷,在對象有多個屬性缺失值、被刪除的含缺失值的對象的數(shù)據(jù)量只占信息表中的數(shù)據(jù)量一小部分的情況下是非常有效的。

python代碼


import numpy as np
import pandas as pd
data = pd.read_csv('data.csv',encoding='GBK')
# 將空值形式的缺失值轉(zhuǎn)換成可識別的類型
data = data.replace(' ', np.NaN)
print(data.columns)#['id', 'label', 'a', 'b', 'c', 'd']
#將每列中缺失值的個數(shù)統(tǒng)計出來
null_all = data.isnull().sum()
#id       0
#label    0
#a        7
#b        3
#c        3
#d        8
#查看a列有缺失值的數(shù)據(jù)
a_null = data[pd.isnull(data['a'])]
#a列缺失占比
a_ratio = len(data[pd.isnull(data['a'])])/len(data) #0.0007
#丟棄缺失值,將存在缺失值的行丟失
new_drop = data.dropna(axis=0)
print(new_drop.shape)#(9981,6)

#丟棄某幾列有缺失值的行
new_drop2 = data.dropna(axis=0, subset=['a','b'])
print(new_drop2.shape)#(9990,6)


2.均值、眾數(shù)、中位數(shù)填充

均值填充:對每一列的缺失值,填充當(dāng)列的均值。

中位數(shù)填充:對每一列的缺失值,填充當(dāng)列的中位數(shù)。

眾數(shù)填充:對每一列的缺失值,填充當(dāng)列的眾數(shù)。

python代碼


data['a'] = data['a'].fillna(data['a'].means())
#中位數(shù)填充
data['a'] = data['a'].fillna(data['a'].median())
#眾數(shù)填充
data['a'] = data['a'].fillna(stats.mode(data['a'])[0][0])
#用前一個數(shù)據(jù)進(jìn)行填充
data['a'] = data['a'].fillna(method='pad')
#用后一個數(shù)據(jù)進(jìn)行填充
data['a'] = data['a'].fillna(method='bfill')


3.填充上下條的數(shù)據(jù)

對每一條數(shù)據(jù)的缺失值,填充其上下條數(shù)據(jù)的值。

python代碼


train_data.fillna(method='pad', inplace=True) # 填充前一條數(shù)據(jù)的值,但是前一條也不一定有值
train_data.fillna(0, inplace=True)
 
train_data.fillna(method='bfill', inplace=True) # 填充后一條數(shù)據(jù)的值,但是后一條也不一定有值
train_data.fillna(0, inplace=True)


4.填充插值得到的數(shù)據(jù)

interpolate()插值法,計算的是缺失值前一個值和后一個值的平均數(shù)。

python代碼


data['a'] = data['a'].interpolate()


5.KNN填充

填充近鄰的數(shù)據(jù),先利用KNN計算臨近的k個數(shù)據(jù),然后填充他們的均值。


from fancyimpute import KNN
fill_knn = KNN(k=3).fit_transform(data)
data = pd.DataFrame(fill_knn)
print(data.head())
#out 
       0    1    2       3         4    5
0  111.0  0.0  2.0   360.0  4.000000  1.0
1  112.0  1.0  9.0  1080.0  3.000000  1.0
2  113.0  1.0  9.0  1080.0  2.000000  1.0
3  114.0  0.0  1.0   360.0 *3.862873 *1.0
4  115.0  0.0  1.0   270.0  5.000000  1.0


6.隨機(jī)森林填充


from sklearn.ensemble import RandomForestRegressor
#提取已有的數(shù)據(jù)特征
process_df = data.ix[:, [1, 2, 3, 4, 5]]
# 分成已知該特征和未知該特征兩部分
known = process_df[process_df.c.notnull()].as_matrix()
uknown = process_df[process_df.c.isnull()].as_matrix()
# X為特征屬性值
X = known[:, 1:3]
# print(X[0:10])
# Y為結(jié)果標(biāo)簽
y = known[:, 0]
print(y)
# 訓(xùn)練模型
rf = RandomForestRegressor(random_state=0, n_estimators=200, max_depth=3, n_jobs=-1)
rf.fit(X, y)
# 預(yù)測缺失值
predicted = rf.predict(uknown[:, 1:3])
print(predicted)
#將預(yù)測值填補(bǔ)原缺失值
data.loc[(data.c.isnull()), 'c'] = predicted
print(data[0:10])
以上就是小編給大家分享的python實現(xiàn)缺失值處理的幾種方法,希望對大家缺失值的處理有所幫助。如果,大家在缺失值處理方面還有哪些好的方法,歡迎隨時和小編交流。


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

若不方便掃碼,搜微信號: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)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時表示是新驗證碼的宕機(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){ //倒計時完成 $(".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); }