pandas.CategoricalIndex.reorder_categories 原文:pandas.pydata.org/docs/reference/api/pandas.CategoricalIndex.reorder_categories.html CategoricalIndex.reorder_categories(*args, **kwargs) 按照new_categories指定的顺序重新排序类别。 new_categories需要包括所有旧的类别,且不包含新的类别项。 参数: new_categories...
add_categories:添加新的分类到尾部 as_ordered:类别排序 as_unordered:使类别无序 remove_categories:去除类别,将被移除的值置为null remove_unused_categories:去除所有未出现的类别 rename_categories:替换分类名,不改变分类的数量 reorder_categories:类进行排序 set_categories:用指定的一组新类替换原来的类,可以添加...
使用categories进行自定义排序。将特定列设置为类型列,并使用CategoricalDtype定义类型顺序。使用astype方法将列转换为自定义类型。之后即可按照此列进行排序。使用set_categories与reorder_categories:set_categories用于设置列的分类,定义新的分类顺序。reorder_categories用于仅更改现有分类的顺序,不改变分类本身。
df['new3'] = df['data'].astype('category').cat.reorder_categories(df['data'].unique()).sort_values().values print(df) 运行之后,结果如下图所示: 方法六 后来【月神】还补充了第三个方法,代码如下图所示: import pandas as pd df = pd.DataFrame({ 'data': ['A1', 'D3', 'B2', 'C4...
CategoricalIndex.rename_categories(*args, …):重命名类别。 CategoricalIndex.reorder_categories(*args, …):重新排序new_categories中指定的类别。 CategoricalIndex.add_categories(args, *kwargs):添加新类别。 CategoricalIndex.remove_categories(*args, …):删除指定的类别。 CategoricalIndex.remove_unused_categor...
Categories (3, object): ['a', 'b', 'c'] 可以将DF中的Series转换为category: In [3]: df = pd.DataFrame({"A": ["a", "b", "c", "a"]}) In [4]: df["B"] = df["A"].astype("category") In [5]: df["B"] Out[32]: ...
(c)利用reorder_categories方法,这个方法的特点在于,新设置的分类必须与原分类为同一集合 代码语言:javascript 代码运行次数:0 运行 AI代码解释 s = pd.Series(["a", "d", "c", "a"]).astype('category') s.cat.reorder_categories(['a','c','d'],ordered=True) 代码语言:javascript 代码运行次数:0...
#分类索引还有一个名为reorder_categories的方法,可以给索引指定一个顺序,分组聚合的结果会按照这个指定的顺序进行呈现 sales_data = [6, 6, 7, 6, 8, 6] index = pandas.CategoricalIndex( # 创建分类索引 data=['苹果', '香蕉', '西瓜', '苹果', '西瓜', '香蕉'], # 索引数据 categories=['苹果...
通过Categorical.reorder_categories()和Categorical.set_categories()方法可以重新排序类别。对于Categorical.reorder_categories(),所有旧类别必须包含在新类别中,不允许有新类别。这将必然使排序顺序与类别顺序相同。 In [102]: s = pd.Series([ 1, 2, 3, 1], dtype="category")In [103]: s = s.cat.reor...
(c)利用reorder_categories方法,这个方法的特点在于,新设置的分类必须与原分类为同一集合 s = pd.Series(["a", "d", "c", "a"]).astype('category')s.cat.reorder_categories(['a','c','d'],ordered=True) #s.cat.reorder_categories(['a','c'],ordered=...