亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

python數據預處理之將類別數據轉換為數值的方法

標簽:
Python

在进行python数据分析的时候,首先要进行数据预处理。

有时候不得不处理一些非数值类别的数据,嗯, 今天要说的就是面对这些数据该如何处理。

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

1,通过LabelEncoder来进行快速的转换;

2,通过mapping方式,将类别映射为数值。不过这种方法适用范围有限;

3,通过get_dummies方法来转换。

import pandas as pdfrom 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)## 遍历Seriesfor 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)


點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消