在進行python數據分析的時候,首先要進行數據預處理。
有時候不得不處理一些非數值類別的數據,嗯, 今天要說的就是面對這些數據該如何處理。
目前了解到的大概有三種方法:
1,通過LabelEncoder來進行快速的轉換;
2,通過mapping方式,將類別映射為數值。不過這種方法適用范圍有限;
3,通過get_dummies方法來轉換。
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) #統計為空的數目 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 構建得到數據 imputed_data = imr.transform(df.values) #transform 將數據進行填充 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, 映射字典將類標轉換為整數 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不適用的 #利用創建一個新的虛擬特征 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數據預處理之將類別數據轉換為數值的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

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