pandas.CategoricalIndex.reorder_categories#
- CategoricalIndex.reorder_categories(*args, **kwargs)[源代码]#
按照 new_categories 中指定的顺序重新排列类别。
new_categories需要包含所有旧类别,并且不包含新的类别项。- Parameters:
- new_categories类索引
按新顺序排列的类别。
- orderedbool, optional
该分类是否被视为有序分类。如果未给出,则不改变有序信息。
- Returns:
- Categorical
类别已重排的分类。
- Raises:
- ValueError
如果新类别不包含所有旧类别项或任何新类别项
参见
rename_categories重命名类别。
add_categories添加新类别。
remove_categories删除指定的类别。
remove_unused_categories删除未使用的类别。
set_categories将类别设置为指定的类别。
Examples
>>> ser = pd.Series(['a', 'b', 'c', 'a'], dtype='category') >>> ser = ser.cat.reorder_categories(['c', 'b', 'a'], ordered=True) >>> ser 0 a 1 b 2 c 3 a dtype: category Categories (3, object): ['c' < 'b' < 'a']
>>> ser.sort_values() 2 c 1 b 0 a 3 a dtype: category Categories (3, object): ['c' < 'b' < 'a']
>>> ci = pd.CategoricalIndex(['a', 'b', 'c', 'a']) >>> ci CategoricalIndex(['a', 'b', 'c', 'a'], categories=['a', 'b', 'c'], ordered=False, dtype='category') >>> ci.reorder_categories(['c', 'b', 'a'], ordered=True) CategoricalIndex(['a', 'b', 'c', 'a'], categories=['c', 'b', 'a'], ordered=True, dtype='category')