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

熱線電話:13121318867

登錄
首頁精彩閱讀4000字歸納總結(jié) Pandas+Sklearn 帶你做數(shù)據(jù)預處理
4000字歸納總結(jié) Pandas+Sklearn 帶你做數(shù)據(jù)預處理
2021-11-24
收藏
4000字歸納總結(jié) Pandas+Sklearn 帶你做<a href='/map/shujuyuchuli/' style='color:#000;font-size:inherit;'>數(shù)據(jù)預處理</a>

作者:俊欣

來源:關(guān)于數(shù)據(jù)分析與可視化

今天我們就來講講數(shù)據(jù)預處理過程當中的一些要點與難點。我們大致會提到數(shù)據(jù)預處理中的

加載數(shù)據(jù)

我們導入必要的庫并且加載數(shù)據(jù)

import pandas as pd
df = pd.read_csv("data.csv")

在進行數(shù)據(jù)分析前,可以查看一下數(shù)據(jù)的總體情況,從宏觀上了解數(shù)據(jù)

data.head() #顯示前五行數(shù)據(jù) data.tail() #顯示末尾五行數(shù)據(jù) data.info() #查看各字段的信息 data.shape #查看數(shù)據(jù)集有幾行幾列,data.shape[0]是行數(shù),data.shape[1]是列數(shù) data.describe() #查看數(shù)據(jù)的大體情況,均值,最值,分位數(shù)值... data.columns.tolist()   #得到列名的list 

處理缺失值

缺失值一直都是數(shù)據(jù)預處理當中比較常見的一個問題,而在處理類似的問題的時候,方式方法也是多種多樣的,我們一一來介紹,

data = [['小明',25,55],['小紅',28,60],['小王',26]] df = pd.DataFrame(data=data,columns=['Name','Age','Weight'])

output

Name Age Weight 0 小明 25 55.0 1 小紅 28 60.0 2 小王 26 NaN 

針對上面的數(shù)據(jù)集,我們通過pandas中的方法看一下缺失值的情況

df.isnull()

output

Name Age Weight 0 False False False 1 False False False 2 False False True 

另外我們也可以這么來做,檢測每一列空值的數(shù)量

df.isnull().sum()

output

Name 0 Age 0 Weight 1 dtype: int64 

而在面對缺失值的時候,我們一方面可以將其去除

df.dropna()

output

Name Age Weight 0 小明 25 55.0 1 小紅 28 60.0 

當然我們也可以對缺失值進行填充,例如用平均值來填充

df.fillna(df.mean())

output

Name Age Weight 0 小明 25 55.0 1 小紅 28 60.0 2 小王 26 57.5 

除了pandas當中的方法之外,我們也可以使用sklearn庫當中的一些函數(shù)方法,例如

from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer = imputer.fit(df[['Weight']])
df['Weight'] = imputer.transform(df[['Weight']])

最后返回的結(jié)果也和上面的fillna()方法返回的結(jié)果一致,我們用平均值來代碼空值,那么同樣道理我們也可以用中位數(shù)眾數(shù)等統(tǒng)計值來進行替換,這里就不做多說

處理離散型數(shù)據(jù)

另外當數(shù)據(jù)集當中出現(xiàn)離散型數(shù)據(jù)的時候,我們也要進行相應(yīng)的處理,畢竟在后面的建模過程當中,機器學習的模型需要的是連續(xù)型的數(shù)據(jù)。

離散型數(shù)據(jù)也分為兩種,一種是有序的離散變量,就比方說是衣服的尺碼,有M碼的、也有L碼的、也還有與之更大的尺碼,另外一種則是無序的,例如衣服的顏色,顏色之間沒有大小之分,因此在編碼的時候也應(yīng)該另外處理。

df_cat = pd.DataFrame(data = 
                     [['green','M',10.1,'class1'],
                      ['blue','L',20.1,'class2'],
                      ['white','M',30.1,'class1']], )
df_cat.columns = ['color','size','price','classlabel']

output

color size price classlabel 0 green M 10.1 class1 1 blue L 20.1 class2 2 white M 30.1 class1 

對于有序的離散型變量,我們可以使用map()函數(shù)

size_mapping = {'M':1,'L':2}
df_cat['size'] = df_cat['size'].map(size_mapping)
df_cat['size']

output

0 1 1 2 2 1 Name: size, dtype: int64 

另外我們也可以使用sklearn庫中的LabelEncoder()方法來處理

from sklearn.preprocessing import LabelEncoder
class_le = LabelEncoder()
df_cat['size'] = class_le.fit_transform(df_cat['size'].values)

而對于無序的離散型變量,我們可以采用獨熱編碼,例如對color這一列進行編碼過之后會有color_green、color_blue以及color_white三個特征,特征值為0或者1

pd.get_dummies(df_cat['color'], prefix = "color")

output

color_blue color_green color_white 0 0 1 0 1 1 0 0 2 0 0 1 

然后我們將此并入到源數(shù)據(jù)當中去

df_cat[["size", "price"]].join(dummies)

output

size price color_blue color_green color_white 0 1 10.1 0 1 0 1 2 20.1 1 0 0 2 1 30.1 0 0 1 

但是考慮到后面搭建模型的時候,變量與變量之間應(yīng)該保持獨立,而不應(yīng)該是存在依賴的關(guān)系,對于color這一列中存在三種顏色,分別是blue、green以及white,當前兩類取值都為0的時候,color只可能是white

所以將get_dummies()方法中的drop_first默認值為False改為True

dummies = pd.get_dummies(df_cat['color'], prefix = "color", drop_first=True)
df_cat[["size", "price"]].join(dummies)

數(shù)據(jù)的標準化

由于不同的變量,它們往往存在不同的單位以及不同的取值范圍,有時候取值范圍的差異較大會對機器學習的模型帶來很多不必要的麻煩。因此為了最后預測結(jié)果的可靠性,我們需要對數(shù)據(jù)進行標準化,對數(shù)據(jù)按比例進行縮放,使之落入一個小的特定區(qū)間。而標準化算法有

  • z-score 標準化

這種方法根據(jù)原始數(shù)據(jù)的均值和標準差進行數(shù)據(jù)的標準化,經(jīng)過處理的數(shù)據(jù)符合正態(tài)分布,即均值為0,標準差為1,計算公式為: = ,當然sklearn庫當中的代碼則是

from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) 
  • 線性歸一化

它的計算公式為: = 當然sklearn庫當中也有相對應(yīng)的代碼

from sklearn.preprocessing import MinMaxScaler()
min_max_scaler = MinMaxScaler()
X_train_minmax = min_max_scaler.fit_transform(X_train) print(X_train_minmax)

訓練集中的數(shù)據(jù)經(jīng)過轉(zhuǎn)化,取值范圍都集中在[0,1]之間

  • MaxAbsScaler()方法

MaxAbsScaler()方法和上述的線性歸一化效果相類似,訓練集中的數(shù)據(jù)經(jīng)過轉(zhuǎn)化,取值范圍在[-1,1]之間

max_abs_scaler = preprocessing.MaxAbsScaler() X_train_maxabs = max_abs_scaler.fit_transform(X_train) X_test_maxabs = max_abs_scaler.transform(X_test)
  • RobustScaler()方法

要是當數(shù)據(jù)集當中存在很多的極值的時候,利用平均值和標準差來進行數(shù)據(jù)的標準化效果可能并不理想,畢竟極值會影響到平均值和標準差的計算,這個時候我們就需要用到RobustScaler()方法,

from sklearn.preprocessing import RobustScaler
transformer = RobustScaler().fit(X)
transformer.transform(X)

數(shù)據(jù)集劃分成訓練集和測試集

在建模之前,我們需要將數(shù)據(jù)集分成訓練集和測試集,我們在訓練集上面建立模型,訓練與優(yōu)化模型,然后再將模型放到測試集上面,評估一下模型的性能以及優(yōu)化的效果,在sklearn庫中也有相對應(yīng)的方法

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2,random_state= 1)

上面的變量y具體指的是被預測的因變量,而x則是在預測中使用的自變量

去除重復值

pandas當中也有對應(yīng)的方法來去除掉重復值

df.drop_duplicates()

數(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(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(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ù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 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); }