假設我們有如下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”列如下: