您可以将^{}与参数category一起使用:cols = ['age','income','student']
for col in cols:
df[col] = df[col].astype('category')
print (df.dtypes)
age category
income category
student category
credit_rating object
Class_buys_computer object
dtype: object
如果需要转换所有列:
^{pr2}$
您需要循环,因为如果使用:df = df.astype('category')NotImplementedError: > 1 ndim Categorical are not supported at this time
按注释编辑:
如果需要有序分类,请使用另一个带有^{}的解决方案:df['age']=pd.Categorical(df['age'],categories=["youth","middle_aged","senior"],ordered=True)
print (df.age)
0 youth
1 youth
2 middle_aged
3 senior
4 senior
5 senior
6 middle_aged
7 youth
8 you