將字元型分類變數資料轉換為數字格式

2021-10-04 16:07:32 字數 597 閱讀 6017

假設我們有如下dataframe,名字為student_weight:

ordered_height = ['short', 'medium', 'tall']#定義順序,這裡是這個次序可以對應,0:short;1,:medium;2:tall;

最後一列out1是字元型分類變數,無法直接被python函式使用,需要進行transform。步驟如下:

student_weight_target=pd.dataframe(student_weight["out1"])#提取「out1」列;

#利用astype將該列變為數字格式;

st=student_weight_target.out1.astype("category",  ordered=true,  categories=ordered_height).cat.codes

student_weight_target["o1"]=pd.dataframe(st)

重新transform的dataframe中的「o1」列如下:

將數字轉換為字串

在日常程式設計中,我們經常需要將各型別的數字轉換為字串,這裡介紹幾種簡單方法。本文沒有介紹轉換的具體演算法。1.使用巨集轉換常量數字為字串 定義如下的巨集 define to string x x 則在 中就可以將各種型別的數字轉換為字串。這個巨集可以將任意的 中的字串轉換為c語言風格的字串 例 t...

將數字字串轉換為數字

將數字字串轉換為數字的方法有多種,c中有atoi,atof,sscanf函式可用,這些函式的用法可以在msdn里查到,這裡就不在多說了,現在說一種通用的轉換的方法 template bool str2value const std string str,type value,std ios base...

將字元數字轉換為數字輸出(模擬atoi)

例如 12345 轉換成12345 我們所所遇到的字串可能有以下幾種情況 include include include enum state state state invalid int my atoi char str while isspace str 跳過字元前面的空格 if str el...