日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

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

系統(tǒng) 1766 0

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

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

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

1,通過LabelEncoder來進(jìn)行快速的轉(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)計(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)

## 遍歷Series
for idx, label in enumerate(df['classlabel']):
  print(idx, label)

#1, 利用LabelEncoder類快速編碼,但此時(shí)對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)建一個(gè)新的虛擬特征
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)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

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

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 阿拉善盟| 铜陵市| 乌审旗| 大名县| 天祝| 金寨县| 洞口县| 镇沅| 望江县| 宁海县| 亳州市| 遵化市| 涞水县| 海淀区| 高邑县| 琼海市| 舞钢市| 阜南县| 乌海市| 天峻县| 高要市| 武夷山市| 渭南市| 宁阳县| 吉木乃县| 渑池县| 白河县| 绥阳县| 锡林郭勒盟| 洞口县| 石棉县| 万宁市| 崇左市| 察哈| 黄浦区| 垦利县| 德庆县| 织金县| 文山县| 高台县| 镇坪县|