Pandas分類數據和順序數據轉換為標志變量


#導入pandas庫
import pandas as pd
#OneHotEncoder用來將數值型類別變量轉換為0-1的標志性變量
#LabelEncoder用來將字符串型變量轉換為數值型變量
from sklearn.preprocessing import OneHotEncoder,LabelEncoder 

#生成數據
df=pd.DataFrame({'id':[321313,246852,447902],
                'sex':['male','Female','Female'],
                'level':['high','low','middle'],
                'score':[1,2,3]})
print(df)
       id     sex   level  score
0  321313    male    high      1
1  246852  Female     low      2
2  447902  Female  middle      3


#拆分id和數據列
id_data=df[['id']] #獲得id列
raw_convert_data=df.iloc[:,1:] #指定要轉換的列
print(raw_convert_data)
      sex   level  score
0    male    high      1
1  Female     low      2
2  Female  middle      3


#將數值型分類向量轉換為標志變量
model_enc=OneHotEncoder() #建立標志轉換模型對象
df_new2=model_enc.fit_transform(raw_convert_data).toarray() #標志轉換


#合並數據
df_all=pd.concat((id_data,pd.DataFrame(df_new2)),axis=1) #重新組合為新數據框
print(df_all) #打印輸出轉換后的數據框
       id    0    1    2    3    4    5    6    7
0  321313  0.0  1.0  1.0  0.0  0.0  1.0  0.0  0.0
1  246852  1.0  0.0  0.0  1.0  0.0  0.0  1.0  0.0
2  447902  1.0  0.0  0.0  0.0  1.0  0.0  0.0  1.0


# 使用pandas的get_dummies做標志轉換
df_new3 = pd.get_dummies(raw_convert_data)
df_all2 = pd.concat((id_data, pd.DataFrame(df_new3)), axis=1)  # 重新組合為數據框
print(df_all2)  # 打印輸出轉換后的數據框
       id  score  sex_Female  sex_male  level_high  level_low  level_middle
0  321313      1           0         1           1          0             0
1  246852      2           1         0           0          1             0
2  447902      3           1         0           0          0             1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM