在進行python數(shù)據(jù)分析的時候,首先要進行數(shù)據(jù)預(yù)處理。
有時候不得不處理一些非數(shù)值類別的數(shù)據(jù),嗯, 今天要說的就是面對這些數(shù)據(jù)該如何處理。
目前了解到的大概有三種方法:
1,通過LabelEncoder來進行快速的轉(zhuǎn)換;
2,通過mapping方式,將類別映射為數(shù)值。不過這種方法適用范圍有限;
3,通過get_dummies方法來轉(zhuǎn)換。
import pandas as pd from io import StringIO csv_data = '''A,B,C,D 1,2,3,4 5,6,,8 0,11,12,''' df = pd.read_csv(StringIO(csv_data)) print(df) #統(tǒng)計為空的數(shù)目 print(df.isnull().sum()) print(df.values) #丟棄空的 print(df.dropna()) print('after', df) from sklearn.preprocessing import Imputer # axis=0 列 axis = 1 行 imr = Imputer(missing_values='NaN', strategy='mean', axis=0) imr.fit(df) # fit 構(gòu)建得到數(shù)據(jù) imputed_data = imr.transform(df.values) #transform 將數(shù)據(jù)進行填充 print(imputed_data) df = pd.DataFrame([['green', 'M', 10.1, 'class1'], ['red', 'L', 13.5, 'class2'], ['blue', 'XL', 15.3, 'class1']]) df.columns =['color', 'size', 'price', 'classlabel'] print(df) size_mapping = {'XL':3, 'L':2, 'M':1} df['size'] = df['size'].map(size_mapping) print(df) ## 遍歷Series for idx, label in enumerate(df['classlabel']): print(idx, label) #1, 利用LabelEncoder類快速編碼,但此時對color并不適合, #看起來,好像是有大小的 from sklearn.preprocessing import LabelEncoder class_le = LabelEncoder() color_le = LabelEncoder() df['classlabel'] = class_le.fit_transform(df['classlabel'].values) #df['color'] = color_le.fit_transform(df['color'].values) print(df) #2, 映射字典將類標(biāo)轉(zhuǎn)換為整數(shù) import numpy as np class_mapping = {label: idx for idx, label in enumerate(np.unique(df['classlabel']))} df['classlabel'] = df['classlabel'].map(class_mapping) print('2,', df) #3,處理1不適用的 #利用創(chuàng)建一個新的虛擬特征 from sklearn.preprocessing import OneHotEncoder pf = pd.get_dummies(df[['color']]) df = pd.concat([df, pf], axis=1) df.drop(['color'], axis=1, inplace=True) print(df)
以上這篇python數(shù)據(jù)預(yù)處理之將類別數(shù)據(jù)轉(zhuǎn)換為數(shù)值的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
