pandas astype categories not working
我厌倦了使用http://pandas.pydata.org/pandas-docs/stable/categorical.html
中的文档将列更改为
1 2 | df = pd.DataFrame({'A':[1,2,3,4,5], 'B':['a','b','c','d','e'], 'C':['A','B','A','B','A']}) df['C']=df['C'].astype('category') |
如果我尝试通过类别
1 | df['C']=df['C'].astype('category',categories=['A','B']) |
误以为是
1 | TypeError: _astype() got an unexpected keyword argument 'categories' |
将类别传递给
您现在需要通过CategorialDtype传递它,因为
1 2 3 | from pandas.api.types import CategoricalDtype df = pd.DataFrame({'A':[1,2,3,4,5], 'B':['a','b','c','d','e'], 'C':['A','B','A','B','A']}) df['C']=df['C'].astype(CategoricalDtype(categories=['A','B'])) |
也属于分类作品。
1 2 | myCategory = ['A','B'] df['C'] = pd.Categorical(df['C'], categories=myCategory, ordered=True) |