国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

python數(shù)據(jù)預(yù)處理之將類別數(shù)據(jù)轉(zhuǎn)換為數(shù)值的方法

2020-01-04 16:56:11
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

在進(jìn)行python數(shù)據(jù)分析的時(shí)候,首先要進(jìn)行數(shù)據(jù)預(yù)處理。

有時(shí)候不得不處理一些非數(shù)值類別的數(shù)據(jù),嗯, 今天要說(shuō)的就是面對(duì)這些數(shù)據(jù)該如何處理。

目前了解到的大概有三種方法:

1,通過(guò)LabelEncoder來(lái)進(jìn)行快速的轉(zhuǎn)換;

2,通過(guò)mapping方式,將類別映射為數(shù)值。不過(guò)這種方法適用范圍有限;

3,通過(guò)get_dummies方法來(lái)轉(zhuǎn)換。

import pandas as pdfrom io import StringIOcsv_data = '''A,B,C,D1,2,3,45,6,,80,11,12,'''df = pd.read_csv(StringIO(csv_data))print(df)#統(tǒng)計(jì)為空的數(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ù)進(jìn)行填充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)## 遍歷Seriesfor idx, label in enumerate(df['classlabel']):  print(idx, label)#1, 利用LabelEncoder類快速編碼,但此時(shí)對(duì)color并不適合,#看起來(lái),好像是有大小的from sklearn.preprocessing import LabelEncoderclass_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 npclass_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)建一個(gè)新的虛擬特征from sklearn.preprocessing import OneHotEncoderpf = 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ù)值的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持VEVB武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 舟曲县| 东海县| 文登市| 常山县| 高阳县| 永州市| 乳源| 宜宾县| 荆州市| 南澳县| 黎城县| 湖北省| 襄城县| 尼木县| 黎城县| 湘潭县| 来安县| 德惠市| 旬邑县| 牟定县| 信宜市| 博野县| 玉屏| 金坛市| 杂多县| 逊克县| 镇康县| 杭州市| 伊通| 麻阳| 泉州市| 三台县| 叙永县| 和龙市| 彩票| 彝良县| 太仓市| 辰溪县| 建水县| 昂仁县| 玛纳斯县|